Here you go:
char[] numArray = num.toCharArray();
int counter=0;
for(int i=0;i<numArray.length;i++) {
if(numArray[i]=='0') {
counter++;
}
if((i==numArray.length-1&&counter>0)||(counter>0&&numArray[i]!='0')) {
System.out.println("Number of Zeroes: "+counter);
counter=0;
}
}
Some important points:
1) It’s best to use an array of char
values here, instead of operating using a double
, because a char
array can store many more values- the example you posted is too long for a double
to handle.
2) Most of this should be self-explanatory (at least, if you study it bit-by-bit), but in case the i==numArray.length-1
part is confusing, this ensures that if the string ends with a 0, the final count of 0’s will be printed out as well.
This should work for any string you can throw at it- including values besides 0 and 1, if you need support for it!
4
solved counting the number of zeros [closed]