题解 | #[NOIP1999]回文数#

[NOIP1999]回文数

https://www.nowcoder.com/practice/a432eb24b3534c27bdd1377869886ebb

#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;

long BaseConverseToDec(string num, int base) {           //将base进制的字符串格式数字转换成十进制数字
    string digits = "0123456789ABCEF";
    long temp = 0;
    for (int j = 0; j < num.length(); j++) {
        for (int i = 0; i < digits.length(); i++) {
            if (digits[i] == num[j]) {
                temp += i * pow(base, num.length() - j - 1);
            }
        }
    }
    return temp;
}
string DecConverseToBase(long decimal, int base) {		//将十进制数字转换成字符串格式数字
    string digits = "0123456789ABCEF";
    string result = "";
    while (decimal > 0) {
        int remainder = decimal % base;
        result = digits[remainder] + result;
        decimal /= base;
    }
    return result.empty() ? "0" : result;
}
string AddNumOutcome(string num, int base)				//将字符串格式数字相加,并输出相应进制的字符串数															字
{
    long temp1 = BaseConverseToDec(num, base);
    reverse(num.begin(),num.end());
    long temp2 = BaseConverseToDec(num, base);
    return num = DecConverseToBase(temp1+temp2,base);
}
bool IsTheSame(string num, int base)				//判断,反转结果是否为回文
{
    string temp = num;
    reverse(temp.begin(), temp.end());
    if(num == temp) return true;
    else return false;
}
int main()
{
    string num;
    int base;
    cin >> base >> num;
    int count = 0;
    while(count < 31)
    {
        count++;
        if(!IsTheSame(num, base)) num = AddNumOutcome(num,base);	//当相加结果不为回文时,将相加结果																		覆盖原值,再进行处理
        else break;
    }
    if(count < 31) cout << "STEP=" << count - 1 << endl;
    else cout << "Impossible!" << endl;
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

机械打工仔:第一位颇有孟德之志
点赞 评论 收藏
分享
06-27 18:53
门头沟学院 Java
这样才知道自己不适合搞代码,考公去咯
只爱喝白开水:我也发现不适合搞代码,打算转非技术方向了
点赞 评论 收藏
分享
见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务