• + 23 comments

    Java solution

    From my HackerRank solutions.

    It seems like the brute-force solution is the best we can do.

    Tips to avoid Integer Overflow

    If you multiply an int with another int, it may cause integer overflow. You can't simply say

    int num = 99999;
    long squared = num * num; // causes integer overflow
    

    since that may cause integer overflow. You need a typecast to convert the int to a long before doing the multiplication.

    int num = 999999;
    long squared = (long) num * num;
    

    Alternatively, you can just store everything as a long

    long num = 999999;
    long squared = num * num;
    

    Also, if there are no Kaprekar numbers, you have to print "INVALID RANGE" exactly as I typed it (without the quotes).

    Working Code - passes 100% of test cases

    import java.util.Scanner;
    
    public class Solution {
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            int p = scan.nextInt();
            int q = scan.nextInt();
            scan.close();
            
            boolean foundKaprekar = false;
            for (int num = p; num <= q; num++) {
                if (isKaprekar(num)) {
                    foundKaprekar = true;
                }
            }
            if (!foundKaprekar) {
                System.out.println("INVALID RANGE");
            }
        }
        
        private static boolean isKaprekar(int num) {
            long squared = (long) num * num;
            String str   = String.valueOf(squared);
            String left  = str.substring(0, str.length() / 2);
            String right = str.substring(str.length() / 2);
            int numL = (left.isEmpty())  ? 0 : Integer.parseInt(left);
            int numR = (right.isEmpty()) ? 0 : Integer.parseInt(right);
            if (numL + numR == num) {
                System.out.print(num + " ");
                return true;
            } else {
                return false;
            }
        }
    }
    

    Let me know if you have any questions.