Not sure if this solution is strictly correct, but it passes all tests...


  • 0
    M

    I have no idea what's the exceptional case for my solution...

    class Solution {
        public String smallestGoodBase(String n) {
            long num = Long.valueOf(n);
            num--;
            long res = -1;
            for (int i = 1; i < 64; i++) {
                long base = (i == 1 ? num : (long) Math.pow(num, 1. / i));
                if (base <= 1) break;
                long val = compute(base, i);
                if (val == num + 1) {
                    res = base;
                }
            }
            return "" + res;
        }
    
        private long compute(long base, int ones) {
            long val = 1;
            while (ones-- > 0) {
                val = val * base + 1; 
            }
            return val;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.