Problem
Reduce the number to 1 in a minimal number of steps, following the rules:
- If the number is even, divide it by 2.
- Otherwise, increment or decrement it by 1.
Limit: s
can be up to 309 digits long.
Solution
public static int solution(String s) {
BigInteger n = new BigInteger(s);
BigInteger one = BigInteger.ONE;
BigInteger two = BigInteger.TWO;
BigInteger four = new BigInteger("4");
int count = 0;
while (n.compareTo(one) == 1) {
count++;
if( n.and(one).intValue() == 0 )
n = n.divide(two);
else if ( n.intValue() == 3 || n.mod(four).intValue() == 1)
n = n.subtract(one);
else
n = n.add(one);
}
return count;
}
Is there a better way to do things binary-operations-wise for this problem?
At the moment the choice I am making among these functions:
- use
n.byteValue()
to compare with the integer, - or use function
n.equals()
.
What more can we improve?
Follow-up question posted here