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

Armstrong Number Validator

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

Problem

Purpose

Validate if a number is an Armstrong Number.

An Armstrong Number is a number


such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 33 + 73 + 13 = 371.

Strategy

  • Calculate the remainder and quotient of the candidate value.



  • While the quotient is greater than 0 and the digit sum is not greater than the candidate value, calculate the new remainder, the new quotient, and add remainder raised by 3 to the digit sum.



Implementation

public class ArmstrongNumberValidatorImpl implements ArmstrongNumberValidator {
    @Override
    public boolean isArmstrong(final long candidate) {
        if (candidate  0 && digitSum <= candidate) {
            remainder = quotient % 10;
            quotient = quotient / 10;
            digitSum += Math.multiplyExact(Math.multiplyExact(remainder, remainder), remainder);
        }

        return (0 == quotient && digitSum == candidate);

    }
}

Solution

Why use multiplyexact?

I'm puzzled why you wrote this:

digitSum += Math.multiplyExact(Math.multiplyExact(remainder, remainder), remainder);


instead of this:

digitSum += remainder * remainder * remainder;


You already know that remainder is a single digit value so computing the cube of it will never overflow.
Extraneous check

Your final return statement could be reduced from this:

return (0 == quotient && digitSum == candidate);


to this:

return (digitSum == candidate);


Your while loop will only terminate on this condition:

quotient == 0 || digitSum > candidate


which means that when digitSum == candidate, quotient must always be 0.

Code Snippets

digitSum += Math.multiplyExact(Math.multiplyExact(remainder, remainder), remainder);
digitSum += remainder * remainder * remainder;
return (0 == quotient && digitSum == candidate);
return (digitSum == candidate);
quotient == 0 || digitSum > candidate

Context

StackExchange Code Review Q#119147, answer score: 7

Revisions (0)

No revisions yet.