首页 技术 正文
技术 2022年11月17日
0 收藏 922 点赞 2,201 浏览 1671 个字

Let’s say a positive integer is a superpalindrome if it is a palindrome, and it is also the square of a palindrome.

Now, given two positive integers L and R (represented as strings), return the number of superpalindromes in the inclusive range [L, R].

Example 1:

Input: L = "4", R = "1000"
Output: 4
Explanation: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.

Note:

  1. 1 <= len(L) <= 18
  2. 1 <= len(R) <= 18
  3. L and R are strings representing integers in the range [1, 10^18).
  4. int(L) <= int(R)

Approach #1: Math. [Java]

class Solution {
public int superpalindromesInRange(String L, String R) {
Long l = Long.valueOf(L), r = Long.valueOf(R);
int result = 0;
for (long i = (long)Math.sqrt(l); i * i <= r;) {
long p = nextP(i);
if (p * p <= r && isP(p * p)) {
result++;
}
i = p + 1;
}
return result;
} private long nextP(long l) {
String s = Long.toString(l);
int N = s.length();
String half = s.substring(0, (N + 1) / 2);
String reverse = new StringBuilder(half.substring(0, N/2)).reverse().toString();
long first = Long.valueOf(half + reverse);
if (first >= l) return first;
String nextHalf = Long.toString(Long.valueOf(half) + 1);
String reverseNextHalf = new StringBuilder(nextHalf.substring(0, N/2)).reverse().toString();
long second = Long.valueOf(nextHalf + reverseNextHalf);
return second;
} private boolean isP(long l) {
String s = "" + l;
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
}

  

Reference:

Calculating the sqrt of nums from [L, R] (denote with ‘s’)

finding the front half of ‘s’ (denote with ‘half’)

the combination of the front half and its reverse (denote with ‘p’)

if p * p >= l and p * p <= r:

  judge p * p is palindromes or not

else :

  Calculating the combination of the front half + 1 and its reverse (denote with ‘p’)   

Reference:

https://leetcode.com/problems/super-palindromes/discuss/170774/Java-building-the-next-palindrome

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,862