当前位置: 代码迷 >> 综合 >> 1024 Palindromic Number (25 分)
  详细解决方案

1024 Palindromic Number (25 分)

热度:68   发布时间:2023-12-05 07:09:07.0

题目链接:1024 Palindromic Number (25 分)

#include<iostream>
using namespace std;
bool judge(int a[],int n)//判断回文数 
{for(int i=0;i<=n/2;i++){if(a[i]!=a[n-1-i]){return false;}}return true;} 
int main()
{int n,b;cin>>n>>b;int a[55],num=0;while(n!=0){a[num++]=n%b;n/=b;}bool flag=judge(a,num);if(flag==true){cout<<"Yes"<<endl;}else{cout<<"No"<<endl;}for(int i=num-1;i>=0;i--){printf("%d",a[i]);if(i!=0){printf(" ");}}return 0;
}
#include <iostream>
#include <vector>
using namespace std;bool check(vector<int>& num)//判断是否是回文数 
{for (int i = 0, j = num.size() - 1; i < j; i ++, j -- )if (num[i] != num[j])return false;return true;
}vector<int> add(vector<int>& a, vector<int>& b)//两个数相加 
{vector<int> c;for (int i = 0, t = 0; i < a.size() || i < b.size() || t; i ++ ){int s = t;if (i < a.size()) s += a[i];if (i < b.size()) s += b[i];c.push_back(s % 10);t = s / 10;}return c;
}int main()
{string n;int k;cin >> n >> k;vector<int> a;for (int i = n.size() - 1; i >= 0; i -- ) {a.push_back(n[i] - '0');} int count = 0;//次数 if (!check(a))//若不是回文数 {while (count < k){vector<int> b(a.rbegin(), a.rend());//将b数组中的数据逆转 a = add(a, b);//两个数相加后结果赋值给a count ++ ;if (check(a)) break;//如果是回文数则退出 }}for (int i = a.size() - 1; i >= 0; i -- ) {cout << a[i];//输出 } cout << endl;cout << count << endl;return 0;
}

方法二

#include <iostream>
#include <algorithm>
using namespace std;
string s;
void add(string t)//两个数相加 
{int len = s.length();//字符串长度 int carry = 0;//进位 for(int i = 0; i < len; i++){s[i] = s[i] + t[i] + carry - '0';carry = 0;if(s[i] > '9') {s[i] = s[i] - 10;carry = 1;}}if(carry) s += '1';reverse(s.begin(), s.end());
}
int main() {int cnt, i;cin >> s >> cnt;for(i = 0; i <= cnt; i++) {string t = s;reverse(t.begin(), t.end());//翻转 if(s == t || i == cnt) break;add(t);//相加 }cout << s << endl << i;return 0;
}

 

  相关解决方案