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)

 

思路:枚举10000内的数字,构造成回文串,再平方以后继续判断。

主要构造回文串的两种方式。偶数项和奇数项

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+8;
const int mod=1e9+7;
class Solution {
public:
    #define LL long long
    bool check(string s) {
        for (int i = 0, j = s.length() - 1; i < j; i++, j--)
            if (s[i] != s[j])
                return false;
        return true;
    }
    int superpalindromesInRange(string L, string R) {
        LL l = stoll(L), r = stoll(R);
        int ans = 0;

        for (int j = 1; j <= 3; j++) {
            if (j * j >= l && j * j <= r)
                ans++;
        }

        for (int i = 1; i < 10000; i++) {
            string t = to_string(i);
            string rt = t;
            reverse(rt.begin(), rt.end());

            LL s = stoll(t + rt);
            s *= s;
            if (s > r)
                break;

            if (check(to_string(s)) && l <= s && s <= r)
                ans++;

            for (char j = '0'; j <= '9'; j++) {
                s = stoll(t + j + rt);
                s *= s;
                if (check(to_string(s)) && l <= s && s <= r)
                    ans++;
            }
        }
        return ans;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值