P1010 [NOIP1998 普及组] 幂次方(十进制转二进制)(递归)
1.P1928 外星密码2.P3612 [USACO17JAN] Secret Cow Code S3.P1259 黑白棋子的移动(函数预处理)
4.P1010 [NOIP1998 普及组] 幂次方(十进制转二进制)(递归)
个人感想
终于能真正自主解决一道纯递归题目了,完成前面那次P1928 外星密码的遗憾了
十进制转化二进制再处理也顺利搞定(之前洛谷月赛就有相似题目,当时觉得很难就没写,太亏了)
十进制转二进制
样例:
int a[]
while (n != 0) {
if (n % 2 == 1) {
a[num] = 1;
} else {
a[num] = 0;
}
num++;
n /= 2;
}
用一个数组来存储二进制数的每一位,就可以很方便的对二进制数做处理(位运算还不懂)
题目思路
跟之前那道题一样,对一个括号内包含括号直接做递归处理,这里要注意一下在2[0],2[1],还有对+号的特判就ok了。
#include <iostream>
#include <string>
#include <math.h>
#include <algorithm>
#include <iomanip>
using namespace std;
int a[100];
void check(int n) {
int b[16];
for (int i = 0; i <= 15; i++) {
b[i] = 0;
}
int num = 0;
while (n != 0) {
if (n % 2 == 1) {
b[num] = 1;
} else {
b[num] = 0;
}
num++;
n /= 2;
}
for (int i = num; i >= 0 ; i--) {
if (b[i] != 0) {
if (i == 1) {
cout << 2;
if (b[0] == 1) {
cout << "+";
}
} else if (i == 0) {
cout << "2(0)";
} else {
cout << 2 << "(";
check(i);
cout << ")";
for (int j = i - 1; j >= 0; j--) {
if (b[j] == 1) {
cout << "+";
break;
}
}
}
}
}
}
int main() {
int n;
cin >> n;
int num = 0;
while (n != 0) {
if (n % 2 == 1) {
a[num] = 1;
} else {
a[num] = 0;
}
num++;
n /= 2;
}
for (int i = num; i >= 0 ; i--) {
if (a[i] != 0) {
if (i == 1) {
cout << 2;
if (a[0] == 1) {
cout << "+";
}
} else if (i == 0) {
cout << "2(0)";
} else {
cout << 2 << "(";
check(i);
cout << ")";
for (int j = i - 1; j >= 0; j--) {
if (a[j] == 1) {
cout << "+";
break;
}
}
}
}
}
return 0;
}
合集:
洛谷递归与递推
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤