-3

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;
}
Abra
  • 19,142
  • 7
  • 29
  • 41
Vanessa
  • 7
  • 5

1 Answers1

0

There are many ways to reverse a number in Java. Refer to Java reverse an int value without using array. In the below code I chose to convert the number to a string and use method reverse of class StringBuilder.

Then you need to subtract the reversed number from the original number and then you need to see whether the result of that subtraction is divisible by the method parameter k. In other words you need to check whether difference % k == 0 where difference is the result of subtracting the reversed number from the original number.

public class MyClass {

    public static int beautifulNum(int from, int to, int k) {
        int reverse = 0;
        int num = 0;
        for (int n = from; n <= to; n++) {
            StringBuilder sb = new StringBuilder(Integer.toString(n));
            sb.reverse();
            reverse = Integer.parseInt(sb.toString());
            int rreverse = n - reverse;
            if (rreverse % k == 0) {
                num++;
            }
        }
        return num;
    }

    public static void main(String args[]) {
        System.out.println(beautifulNum(20, 23, 6));
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41