The following is my solution to Beautiful Days at the Movies problem on HackerRank.
Basically I need to implement the following method.
int beautifulNum(int from, int to, int k)
The method should return the number of beautiful numbers between from
and to
.
A number is beautiful if the result of its difference with its reverse is divisible by k
.
Example:
beautifulNum(20, 23, 6)
should return 2.
- Reverse of 20 is 2. Difference is 18 which is divisible by 6 so 20 is a beautiful number.
- Reverse of 21 is 12. Difference is 9 which is not divisible by 6 hence 21 is not a beautiful number.
- Similarly, 22 is a beautiful number and 23 is not.
- Therefore
beautifulNum(20, 23, 6)
should return 2.
However, the following does not work, why?
public static int beautifulNum(int from, int to, int k) {
int reverse = 0;
int num = 0;
for (int n = from; n <= to; n++) {
while(n != 0) {
int remainder = n % 10;
reverse = reverse * 10 + remainder;
n = n/10;
}
int rreverse = (n-reverse)/k;
if (rreverse % 1 == 0 ) {
num++;
}
}
return num;
}