回文数
Description
Farmer John has been branding the cows with a serial number ever since he started the farm. The new cow fad is 'RADAR' brands, so-called because they read the same forwards and backwards (they are palindromic). All the cows want their daughters branded in the new RADAR style.
Each mother wants her daughter's brand to be derived from her own non-RADAR brand by summing the mother's brand and its reverse. Sometimes (e.g., 12 + 21 = 33) this yields a RADAR palindrome right away. Sometimes the process must be repeated several times until a RADAR brand emerges. Consider the brand '87' that requires four steps to convert to a RADAR brand:
Brand Reverse Sum
Step 1: 87 + 78 = 165
Step 2: 165 + 561 = 726
Step 3: 726 + 627 = 1353
Step 4: 1353 + 3531 = 4884
Given the mother's brand (a positive integer), determine the number of steps and ultimate RADAR brand that results from applying the procedure above. No answer will be greater than two billion.
题目大意是输入n,若不是回文数,则将n反转和n求和得到新的n,再判断n是否为回文数,问几次这样的操作可以使得最开始的n变成回文数。
示例输入
87
示例输出
4 4884
#include <stdio.h>
int main(void)
{
int brand, reverse = 0, sum = 0;
int num = 0, rsum = 0, step = 0;
scanf("%d", &brand);
while (1) {
num = brand;//存储brand原值
reverse = 0;//初始化清零,方便下一次使用
while (num) {//翻转brand值
reverse = reverse * 10 + num % 10;
num /= 10;
}
sum = brand + reverse;
num = sum;//存储sum原值
rsum = 0;//初始化,因为上一步的rsum未清零
while (num) {//将sum值翻转与原值比较
rsum = rsum * 10 + num % 10;
num /= 10;
}
printf("step is %d, %d + %d = %d.\n", step + 1, brand, reverse, sum);
if(sum == rsum) {//若相等则为回文数,退出循环
printf("step's num is %d, the value is %d.\n", step + 1, sum);
break;
}
//否则将sum值赋给brand,重新进行上述操作,直到最后sum值为回文数
brand = sum;
step++;//记录步骤
}
return 0;
}
运行结果