zoukankan      html  css  js  c++  java
  • 906. Super Palindromes

    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

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    注册表解锁
    Windows错误代码大全 2
    硬盘数据线的问题
    vs2010与C#4.0新特性
    (转载)C语言负数的移位运算
    (转载)看C语言编码转换负数的二进制表示方法
    (转载)C语言右移运算符的问题(特别当与取反运算符一起时)
    (转载)Qt中使用cout输出的方法
    (转载)QPainter的用法
    (转载)Qt计算MD5
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10914667.html
Copyright © 2011-2022 走看看