// count odd length; for (intk=1; k < MAGIC; ++k) { StringBuildersb=newStringBuilder(Integer.toString(k)); for (inti= sb.length() - 2; i >= 0; --i) sb.append(sb.charAt(i)); longv= Long.valueOf(sb.toString()); v *= v; if (v > R) break; if (v >= L && isPalindrome(v)) ans++; }
// count even length; for (intk=1; k < MAGIC; ++k) { StringBuildersb=newStringBuilder(Integer.toString(k)); for (inti= sb.length() - 1; i >= 0; --i) sb.append(sb.charAt(i)); longv= Long.valueOf(sb.toString()); v *= v; if (v > R) break; if (v >= L && isPalindrome(v)) ans++; }
return ans; }
publicbooleanisPalindrome(long x) { return x == reverse(x); }
publiclongreverse(long x) { longans=0; while (x > 0) { ans = 10 * ans + x % 10; x /= 10; }
defreverse(x): ans = 0 while x: ans = 10 * ans + x % 10 x /= 10 return ans
defis_palindrome(x): return x == reverse(x)
ans = 0
# count odd length for k in xrange(MAGIC): s = str(k) # Eg. s = '1234' t = s + s[-2::-1] # t = '1234321' v = int(t) ** 2 if v > R: break if v >= L and is_palindrome(v): ans += 1
# count even length for k in xrange(MAGIC): s = str(k) # Eg. s = '1234' t = s + s[::-1] # t = '12344321' v = int(t) ** 2 if v > R: break if v >= L and is_palindrome(v): ans += 1
return ans
复杂度分析
时间复杂度:O(W^{1/4}} * \log W),其中 W = 10^{18 是 R 的上界。\log W 是用来检验每个候选数字是否为回文数。