checking an integer to see if it contains a zero

前端 未结 7 1798
南方客
南方客 2020-12-14 21:09

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 c

7条回答
  •  醉话见心
    2020-12-14 21:37

    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.

提交回复
热议问题