checking an integer to see if it contains a zero

前端 未结 7 1781
南方客
南方客 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:20

    Here is a routine that will work detect zeros in integers. To make it work with any representation (decimal, hex, octal, binary), you need to pass in the base as a parameter.

    public static boolean hasZero(int num, int base) {
        assert base > 0 : "must have positive non-zero base";
    
        if (num == 0)
            return true;
    
        while(num != 0) {
            if (num % base == 0) {
                return true;
            }
            else {
                num = num / base;
            }
        }
    
        return false;
    }
    
    public static void main(String args[]) {
        System.out.println(hasZero(10, 10));  // true (base 10 int)
        System.out.println(hasZero(-12, 10));  // false (base 10 int)
    
        System.out.println(hasZero(0x10, 16)); // true (hex is base 16)
        System.out.println(hasZero(0x1A, 16)); // false (hex is base 16)
    }
    

提交回复
热议问题