大于N的最小回文数

12 篇文章 0 订阅
6 篇文章 0 订阅

题目描述

Palindromic numbers are digital strings that read the same both forwards and backwards. For example, 121, 44 and 3 are Palindromic numbers, 175, 36 are not;
For a given integer N, you are to find a palindromic number P that satisfy P>N. However, there are many such palindromic numbers. Your task is to find the least one.

输入

There are several test cases, each test case contains only one positive integer N in one line. The number of digits of N is not exceeding 10,000, and N has not lead zeroes.
The input will finish with the end of file.

输出

For each the case, your program will output the least palindromic number P (P > N) on separate line.

样例输入

44
3
175

样例输出

55
4
181

来源

2011ACM/ICPC 第五届华中南赛区邀请赛 

题解

思路
题意要求,数N可达10000位,只能用字符串数组存储,对于回文数,只要求前半部分就可写出后半部分,大致分两种情况,一种是前半部分小于后半部分,前半部分有要+1的,这时候就要判断是否有9,有9存在要增加一位的情况,如999/199/191。另一种简单,因为前半部分大于后半部分,所以,只要把前半部分替换后半部分即可,如321/291.
测试数据

89999
1231
12351
9998
9898
2993
1000
100
192
291
121
99
999
2
10
1991
19991
19191

代码如下
#include <cstdio>
#include <cstring>
#define N 10001
char s[N];
using namespace std;
int main(){
    while ( ~scanf("%s",s)){
        int len=strlen(s);
        int flag=0,i;
        for(i=len/2-1;i>=0;--i){
            if(s[i]>s[len-1-i]){flag=1;break;}
            else if(s[i]<s[len-1-i]){ flag=-1;break;}
        }
        if(flag!=1){//前半串要加1
            //s[(len-1)/2]++;
            for(i=(len-1)/2;i>=0;--i){//199 191 999
                s[i]++;
                if(s[i]>'9'){
                    s[i]='0';
                }else break;
            }
            if(s[0]=='0'){//999 9999
                s[0]='1';
                len++;
                s[len/2]='0';
            }
        }
        for(i=0;i<len/2;++i)
            printf("%c",s[i]);
        for(i=(len+1)/2-1;i>=0;--i)
            printf("%c",s[i]);
        printf("\n");
    }
    return 0;
}
  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值