【题意分析】1024 Palindromic Number (25 分)_38行代码AC
立志用最少的代碼做最高效的表達
PAT甲級最優(yōu)題解——>傳送門
A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example, 1234321 is a palindromic number. All single digit numbers are palindromic numbers.
Non-palindromic numbers can be paired with palindromic ones via a series of operations. First, the non-palindromic number is reversed and the result is added to the original number. If the result is not a palindromic number, this is repeated until it gives a palindromic number. For example, if we start from 67, we can obtain a palindromic number in 2 steps: 67 + 76 = 143, and 143 + 341 = 484.
Given any positive integer N, you are supposed to find its paired palindromic number and the number of steps taken to find it.
Input Specification:
Each input file contains one test case. Each case consists of two positive numbers N and K, where N (≤10^10) is the initial numer and K (≤100) is the maximum number of steps. The numbers are separated by a space.
Output Specification:
For each test case, output two numbers, one in each line. The first number is the paired palindromic number of N, and the second number is the number of steps taken to find the palindromic number. If the palindromic number is not found after K steps, just output the number obtained at the Kth step and K instead.
Sample Input 1:
67 3
Sample Output 1:
484
2
Sample Input 2:
69 3
Sample Output 2:
1353
3
題意:給定數(shù)N,次數(shù)K,將N翻轉(zhuǎn)后與原數(shù)相加,判斷是否為回文數(shù),如果是則直接輸出,如果不是,則算作一次操作,操作次數(shù)上限為K。若K次后仍不是回文數(shù),則直接輸出該數(shù),結(jié)束循環(huán)。
分析:利用了字符串函數(shù)翻轉(zhuǎn)機制縮減了代碼量。代碼邏輯很簡單,讀者可自行體會。
#include<bits/stdc++.h> using namespace std;bool is_palindormic(string s) { //判斷是否是回文數(shù) string s1 =s;reverse(s.begin(), s.end());if(s1 == s) return true;else return false; }string ope (string s) { //執(zhí)行相加操作 string s1 = s, add_s;reverse(s.begin(), s.end());int carry = 0, x;for(int i = 0; i < s.size(); i++) {x = (s[i]-'0' + s1[i]-'0' + carry) % 10;carry = (s[i]-'0' + s1[i]-'0' + carry) / 10;add_s += x+'0';}if(carry > 0) add_s += carry+'0';reverse(add_s.begin(), add_s.end());return add_s; }int main() {string s; int n, n1;cin >> s >> n;n1 = n;while(n1) if(is_palindormic(s)) { //如果是回文數(shù),則輸出,結(jié)束循環(huán) cout << s << '\n' << n-n1 << '\n'; goto loop;} else { //如果不是回文數(shù), n1--;s = ope(s);}cout << s << '\n' << n << '\n'; loop : ;return 0; }
耗時:
超強干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的【题意分析】1024 Palindromic Number (25 分)_38行代码AC的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【详细分析】1023 Have Fun
- 下一篇: 1027 Colors in Mars