洛谷 - B4276 [蓝桥杯青少年组国赛 2023] 八进制回文平方数 - 题解

题目传送门

主要思路

首先,这道题范围在 \(10^9\),我们不可能直接从 \(1\) 循环到 \(N\)。我们不难看出,这道题是求平方数的八进制是否回文,那些不是平方数的例如 \(2\) 呀,\(3\) 呀这些都是不用考虑的。我们循环也只用从 \(1\) 到 \(\left\lfloor\sqrt{n}\right\rfloor\) 就可以了。这样,时间复杂度就大大降低了。其余部分就没什么好说的了,详见代码。

AC 代码:

cpp 复制代码
#include<iostream>
using namespace std;
string l0z8(int n){
    string s;
    while(n){
        s=char(n%8+48)+s;
        n/=8;
    }
    return s;
}
bool isHw(int n){
    string s=l0z8(n);
    int l=0,r=s.size()-1;
    while(l<=r){
        if(s[l]!=s[r])return 0;
        l++,r--;
    }
    return 1;
}
int main(){
    int n;
    cin>>n;
    for(int i=1;i*i<=n;i++){
        if(isHw(i*i)){
            cout<<i*i<<' ';
        }
    }
    return 0;
}

代码时间复杂度:\(\mathcal O\left(4\times\log_88\times\left\lfloor\sqrt{n}\right\rfloor\right)\)

相关推荐
布朗克1688 天前
Go 入门到精通-16-字符串深入
开发语言·后端·golang·字符串
鱼子星_8 天前
【C++】string(上):string的基本使用
c++·笔记·字符串
csdn_aspnet18 天前
C# 提取、截取或匹配字符串内包含指定字符的一些方法分享
c#·字符串·正则·分割·提取·匹配
csdn_aspnet18 天前
C# 截取或匹配字符串内包含指定字符的一些方法
c#·字符串·分割·string·匹配·截取
csdn_aspnet19 天前
C# 截取或匹配字符串内包含指定字符
c#·字符串·正则·string·匹配·截取
Tisfy21 天前
LeetCode 1358.包含所有三种字符的子字符串数目:滑动窗口(两种写法直接推荐方法二)
算法·leetcode·字符串·题解·滑动窗口
Tisfy1 个月前
LeetCode 3838.带权单词映射:求和、取模、拼接(附python一行版)
python·算法·leetcode·字符串·题解·模拟·取模
阿方.9182 个月前
C++ string 超全精讲 | 从零使用、底层原理、手搓简易string、高频考点、易错点、面试手撕
开发语言·c++·字符串·string·知识分享
罗湖老棍子2 个月前
The xor-longest Path(信息学奥赛一本通- P1478)
算法·字符串·字典树··lca最近公共祖先
金创想2 个月前
积木移动题目分析及解题思路——木块问题(1)
c++·算法·字符串·c·刷题·信息学奥赛·积木