Anyone having an acceptable Java solution which uses log calculations ?


  • 0
    A

    I've been stumped in trying to write Java code which is accepted, which also uses log calculations, but the rounding errors are really pissing me off. Looking at the solutions others have posted, I haven't found a single solution which uses log calculations.

    The following code is theoretically correct, but because of rounding issues it fails:

    public class Solution {
    public boolean isPowerOfThree(int n) {

        if(n <= 0) {
            return false;
        } else {
            
            double x = Math.log(n) / Math.log(3);
            
            if (x - Math.floor(x) == 0) {
                return true;
            } else {
                return false;
            }
        }
    }
    

    }

    I also tried using BigDecimal, but this approach also fails for some tests:

    public class Solution {
    public boolean isPowerOfThree(int n) {

        if(n <= 0) {
            return false;
        } else {
            
            BigDecimal top = BigDecimal.valueOf(Math.log(n) + 0d);
            BigDecimal bottom = BigDecimal.valueOf(Math.log(3) + 0d);
            BigDecimal x = top.divide(bottom, 20, RoundingMode.HALF_UP);
            BigDecimal xFloor = x.setScale(0, RoundingMode.FLOOR);
            
            if(x.compareTo(xFloor) == 0) {
                return true;
            } else {
                return false;
            }
        }
    }
    

    }

    Any ideas how to get these to work while still using log calculations ?


  • 0

Log in to reply
 

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