当前位置: 移动技术网 > 移动技术>移动开发>IOS > PAT A1136 回文数

PAT A1136 回文数

2020年07月15日  | 移动技术网移动技术  | 我要评论

1. 题意

给出1000位的数,判断是否是回文数。10次相加还不是回文数,输出。

2. 代码

  1. 最后一组数据超过long long,不能使用stoll(str)
  2. 开局判断是否是回文数,是的话直接输出 %s is a palindromic number.
  3. 算法笔记大整数运算。
  4. 如果全程使用string,在大整数加法时要给出大小。否则不能使用str[i]=temp。加法完成后还要再str.resize(len)一次。
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

bool is_palindromic(string str) {
  string str1 = str;
  reverse(str1.begin(), str1.end());
  return str1 == str;
}

string add_str(string str1, string str2) {    //有可能进位
  string ans;
  ans.resize(1010);
  int carry = 0;
  int len = 0;
  reverse(str1.begin(), str1.end());
  reverse(str2.begin(), str2.end());
  for (int i = 0; i < str1.size(); ++i) {
    int temp = str1[i] - '0' + str2[i] - '0' + carry;
    char s = temp % 10 + '0';
    ans[len++] = s;
    carry = temp / 10;
  }
  if (carry != 0) ans[len++] = carry + '0';
  ans.resize(len);
  reverse(ans.begin(), ans.end());
  return ans;

}

int main() {
  string str1, str2, ans;
  cin >> str1;
  if (is_palindromic(str1)) {    //特判
    printf("%s is a palindromic number.", str1.c_str());
    return 0;
  }

  for (int i = 0; i < 10; ++i) {
    str2 = str1;
    reverse(str1.begin(), str1.end());
    //ans = to_string(stoll(str1) + stoll(str2)); //stoi可能越界
    ans = add_str(str1, str2);
    if (is_palindromic(ans)) {   //是回文数
      printf("%s + %s = %s\n", str2.c_str(), str1.c_str(), ans.c_str());
      printf("%s is a palindromic number.\n", ans.c_str());
      return 0;
    } else {  //不是回文数
      printf("%s + %s = %s\n", str2.c_str(), str1.c_str(), ans.c_str());
      str1 = ans;
    }
  }
  printf("Not found in 10 iterations.");
  return 0;

}

本文地址:https://blog.csdn.net/weixin_41945646/article/details/107340990

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网