Given a binary string (containing 1’s and 0’s), write a program to count the number of 0’s in a given string such that the following conditions hold:
- 1’s and 0’s are in any order in a string
- Use of conditional statements like if, if..else, and switch are not allowed
- Use of addition/subtraction is not allowed
Examples:
Input : S = “101101”
Output : 2Input : S = “00101111000”
Output : 6
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Approach: The above problem can be solved with the below idea:
If counter and conditional statements are not allowed. We are having option of Error handling.
Steps involved in the implementation of the approach:
- Take a string and a static variable counter which maintain the count of zero.
- Traverse through each character and convert it into an integer.
- Take this number and use it as a denominator of the number “0”.
- Use the exception handling method try..catch in a loop such that whenever we got the Arithmetic exception, the counter will increment.
- Print the counter value as a result.
Below is the implementation of the above approach:
Java
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Related Articles: