Count number of 0’s with given conditions

Improve Article

Save Article

Like Article

Improve Article

Save Article

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


Input : S = “101101”
Output : 2

Input : 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:




class GFG {



    public static int cnt = 0;


    public static void main(String[] args)



        String s = "01001001110";








    static void countZero(String s)



        for (int i = 0; i < s.length(); i++) {

            try {

                int div = Character.getNumericValue(






                int val = 0 / div;




            catch (Exception exception) {









Time Complexity: O(N)
Auxiliary Space: O(1)

Related Articles:

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: