Different results of using log() and log10()


  • 0
    N

    When asked to solve it in O(1) time and using O(1) space, I came up with formula solution.

    This is my first version and it failed in input n = 536870912.

    public class Solution {
        public boolean isPowerOfTwo(int n) {
            double k = Math.log(n)/Math.log(2);
            return k - Math.floor(k) == 0;
        }
    }
    

    However, it gets accpeted after I replace Math.log() to Math.log10()

    Anyone knows why?


  • 0

    Well what exactly is k when you use log and what exactly is it when you use log10?

    With different intermediate results that get rounded differently, it's not surprising that you can get different results.


Log in to reply
 

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