Check if one integer is an integer power of another

后端 未结 13 1542
臣服心动
臣服心动 2020-11-27 05:15

This is an interview question: \"Given 2 integers x and y, check if x is an integer power of y\" (e.g. for x = 8 and y = 2 the answer is \"true\", and for x = 10 and y = 2 \

13条回答
  •  执笔经年
    2020-11-27 05:32

    It means logy(x) should be an integer. Don't need any loop. in O(1) time

    public class PowerTest {
    
        public static boolean isPower(int x, int y) {
            double d = Math.log(Math.abs(x)) / Math.log(Math.abs(y));
    
            if ((x > 0 && y > 0) || (x < 0 && y < 0)) {
                if (d == (int) d) {
                    return true;
                } else {
                    return false;
                }
            } else if (x > 0 && y < 0) {
                if ((int) d % 2 == 0) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
    
            System.out.println(isPower(-32, -2));
            System.out.println(isPower(2, 8));
            System.out.println(isPower(8, 12));
            System.out.println(isPower(9, 9));
            System.out.println(isPower(-16, 2));
            System.out.println(isPower(-8, -2));
            System.out.println(isPower(16, -2));
            System.out.println(isPower(8, -2));
        }
    
    }
    

提交回复
热议问题