HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Checking whether a number is a power of 10

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numbercheckingwhetherpower

Problem

Is there a better way to check whether a number is a power of 10? This is what I've implemented:

public class PowersOfTen {

    public static boolean isPowerOfTen(long input) {

        if (input % 10 != 0 || input == 0) {
            return false;
        }

        if (input == 10) {
            return true;
        }

        return isPowerOfTen(input/10);
    }

    public static void main(String[] args) {

        System.out.println("1000: " + isPowerOfTen(1000));
        System.out.println("4: " + isPowerOfTen(4));
        System.out.println("0: " + isPowerOfTen(0));
        System.out.println("10: " + isPowerOfTen(10));
        System.out.println("100: " + isPowerOfTen(100));
    }
}

Solution

Recursing seems pretty heavy for this. You can use much the same logic but with a simple loop:

while (input >= 10 && input % 10 == 0) 
  input /= 10;
return input == 1;


This checks to make sure the input is at least 10 (since any integers below that, including zero and negative values, can't be powers of 10) and also a multiple of 10 (as all powers of 10 greater than 1 obviously are). It does the simpler comparison first as a small micro-optimization; the short-circuit evaluation will avoid performing an unnecessary division to compute an unneeded modulus.

If both conditions are met it does an integer division by 10 and repeats the process. For any power of 10, this will terminate with the value 1; if 1 itself is passed in, it will do so without ever executing the body of the while loop.

Code Snippets

while (input >= 10 && input % 10 == 0) 
  input /= 10;
return input == 1;

Context

StackExchange Code Review Q#117203, answer score: 44

Revisions (0)

No revisions yet.