-
Notifications
You must be signed in to change notification settings - Fork 23
/
906. Super Palindromes
55 lines (46 loc) · 1.6 KB
/
906. Super Palindromes
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public int superpalindromesInRange(String left, String right) {
long l = Long.valueOf(left);
long r = Long.valueOf(right);
int count = 0;
//Create the palindromes in range 1, 100000
//Even Palindromes
for(int i = 1; i < 100000; i++) {
StringBuilder sb = new StringBuilder(Integer.toString(i));
for(int j = sb.length()-1; j >= 0; j--) {
sb.append(sb.charAt(j));
}
//Palindrome in sb
long n = Long.valueOf(sb.toString());
n*=n;
//Check if n is a super palindrome --> Find whether it is palindrome
if(n > r) break;
else if(n>=l && isPalindrome(n)) count++;
}
//Odd Palindromes
for(int i = 1; i < 100000; i++) {
StringBuilder sb = new StringBuilder(Integer.toString(i));
for(int j = sb.length()-2; j >= 0; j--) {
sb.append(sb.charAt(j));
}
//Palindrome in sb
long n = Long.valueOf(sb.toString());
n*=n;
//Check if n is a super palindrome --> Find whether it is palindrome
if(n > r) break;
else if(n>=l && isPalindrome(n)) count++;
}
return count;
}
public boolean isPalindrome(long n) {
return n == reverse(n);
}
public long reverse(long n) {
long rev = 0;
while(n > 0) {
rev = rev*10 + n%10;
n/=10;
}
return rev;
}
}