C语言:若一个数不是回文数,则将n反转和n求和得到新的n,再判断n是否为回文数

回文数

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;
}

运行结果

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值