Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking an integer to see if it contains a zero

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?

like image 443
Bobby S Avatar asked Oct 02 '10 20:10

Bobby S


People also ask

How check if an integer contains an number in C++?

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.

How do you check if a number contains a certain digit in Java?

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.


1 Answers

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.

like image 78
Bill the Lizard Avatar answered Oct 08 '22 15:10

Bill the Lizard