【PAT甲级题解记录】1019 General Palindromic Number (20 分)

【PAT甲级题解记录】1019 General Palindromic Number (20 分)

前言

Problem:1019 General Palindromic Number (20 分)

Tags:进制转换 回文串判断

Difficulty:剧情模式 想流点汗 想流点血 死而无憾

Address:1019 General Palindromic Number (20 分)

问题描述

给定一个正整数N,求其作为b进制数时是否为回文数。

解题思路

  • 进制转化完后存储下来,半个循环对比左右数值即可。( N N N is palindromic if and only if a i = a k − i a_i=a_k−i ai=aki for all i i i. 其中 k k k是数组长度)
  • 转换后的b进制数可用一个数组来表示。

参考代码

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int N, b; // 1e9
void init() {
    cin >> N >> b;
}

vector<int> Decimal_to(int n, int base) {
    vector<int> ans;
    if(n==0){
        ans.push_back(0);
        return ans;
    }
    while (n) {
        ans.push_back(n % base);
        n /= base;
    }
    reverse(ans.begin(), ans.end()); // 其实要判断是否回文,是否反转不影响,但这里将其当成一个单纯的通用型函数
    return ans;
}

void printNum(const vector<int> &v) {
    for (int i = 0; i < int(v.size()); ++i) {
        cout << (i > 0 ? " " : "") <<v[i];
    }
    cout<<endl;
}

void solution_1019() {
    init();
    vector<int> ans = Decimal_to(N, b);
    for (int i = 0; i < int(ans.size()) / 2 + 1; ++i) {
        if (ans[i] != ans[int(ans.size()) - 1 - i]) {
            cout << "No" << endl;
            printNum(ans);
            return;
        }
    }
    cout << "Yes" << endl;
    printNum(ans);
}
int main() {
    solution_1019();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值