UVa 10018 Reverse and Add
解題策略
這題是這樣的,要把輸入的數字反轉,例如1357變成7531,然後與原數相加。直到這個數字變成迴文(palindrome)為止,像是1357+7531=8888,8888就是一個迴文。本題只需要按照著要求計算即可,唯一比較技巧是反轉一個整數 int:reverse()注意
需要注意變數範圍:至少要 unsigned long 才能容納題目的數字範圍。而printf()、scanf() 與 unsigned long 打交道的代號是%lu。爭議點
這題有個爭議點是第一個數字到底需不需要判斷回文,舉個例子:輸入2,那麼該輸出0 2或者1 4?舊版的UVa測資要求必須要輸出1 4,這有些不合常理,新版則是把爭議性測資都拿掉了,所以兩種寫法都能AC。但是在zerojudge.tw上就必須輸出1 4才行。
PS.這題我不小心把某個unsigned long打成int,抓了好久的bug。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* UVa 10018 Reverse and Add | |
* Author: chchwy (a) gmail.com | |
* Last modified: 2010.07.27 | |
*/ | |
#include<cstdio> | |
unsigned long reverse(unsigned long n) | |
{ | |
unsigned long rev_n = 0; //WA : int rev_n = 0; | |
while (n != 0) | |
{ | |
rev_n = (rev_n * 10) + n % 10; | |
n /= 10; | |
} | |
return rev_n; | |
} | |
inline int is_palindrome(unsigned long n) | |
{ | |
return (n == reverse(n)) ; | |
} | |
int reverse_and_add(unsigned long num, unsigned long& result) | |
{ | |
int counter = 0; | |
do | |
{ | |
num += reverse(num); | |
counter++; | |
} | |
while ( !is_palindrome(num) ); | |
result = num; | |
return counter; | |
} | |
int main() | |
{ | |
#ifndef ONLINE_JUDGE | |
freopen("10018.in", "r", stdin); | |
#endif | |
int numOfCase; | |
scanf("%d", &numOfCase); | |
while (numOfCase--) | |
{ | |
unsigned long num; | |
scanf("%lu", &num); | |
int iteration; // the number of iterations | |
unsigned long result; // the final palindrome, like 9339 | |
iteration = reverse_and_add(num, result); | |
printf("%d %lu\n", iteration, result); | |
} | |
return 0; | |
} |
留言
張貼留言