首页 > 其他 > 详细

906. Super Palindromes

时间:2019-05-23 22:05:16      阅读:122      评论:0      收藏:0      [点我收藏+]

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

 

906. Super Palindromes

原文:https://www.cnblogs.com/ruruozhenhao/p/10914667.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!