Given an integer, how could you check if it contains a 0, using Java?
1 = Good 2 = Good ... 9 = Good 10 = BAD! 101 = BAD! 1026 = BAD! 1111 = Good
How can this be done?
Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.
To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.
If for some reason you don't like the solution that converts to a String you can try:
boolean containsZero(int num) {
if(num == 0)
return true;
if(num < 0)
num = -num;
while(num > 0) {
if(num % 10 == 0)
return true;
num /= 10;
}
return false;
}
This is also assuming num
is base 10.
Edit: added conditions to deal with negative numbers and 0 itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With