-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Solution.java
38 lines (34 loc) · 1.15 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// github.com/RodneyShag
import java.util.Scanner;
// Brute-force solution
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; // multiplying 2 ints without typecast could cause overflow
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;
}
}
}