22169 回文对称数

回文对称数

链接:https://ac.nowcoder.com/acm/problem/22169
来源:牛客网

题目描述
今天牛牛学到了回文串,他想在数字里面找回文,即回文数,回文数是正着读与倒着读都一样的数,比如1221,343是回文数,433不是回文数。请输出不超过n的回文数。
输入描述:
输入一个整数n(1 <= n <= 100000)
输出描述:
从1开始按从小到大的顺序输出所有回文数
示例1
输入

10

输出

1
2
3
4
5
6
7
8
9

代码:

#include<stdio.h>
#include<string.h>
bool huiwen(int n){
    int i;
    int len = 0;
    int a[7] = {0};
    while(n != 0 ){
        a[len] = n%10;
        n /= 10;
        len++;
    }
    for(i = 0;i<len/2+1;i++){
        if(a[i] != a[len-1-i])    break;
    }
    if(i == len/2+1) return true;
    else return false;
}
int main(){
    int n,i;
    scanf("%d",&n);
    for(i = 1;i<n+1;i++){
        if(huiwen(i))    printf("%d\n",i);
    }
    return 0;
}

还是字符数组好用一些,可以用string头文件里面的一些字符串函数。比如说:strlen(str)等等。

#include<stdio.h>
#include<string.h>
bool huiwen(int x){
    int j = 0;
    char a[7];
    while(x != 0 ){
        a[j] = x % 10 +'0';
        x /= 10;
        j ++;
    }
    
    for(j = 0;j<strlen(a)/2+1;j++){
        if(a[j] != a[strlen(a)-1-j])    break;
    }
    if(j == strlen(a)/2+1) return true;
    else return false;
}
int main(){
    int n,i;
    scanf("%d",&n);
    for(i = 1;i<n+1;i++){
        if(huiwen(i))    printf("%d\n",i);
    }
    return 0;
}

但其实好像都一样,并没有简便多少。。。

其实这个题我做复杂了,我看了一种更简单的方法。

#include<stdio.h>
#include<string.h>
bool huiwen(int x){
    int temp = x;
    int sum = 0;
    while(x != 0 ){
        sum = sum*10 + x % 10;
        x /= 10;
    }
    if(sum == temp) return true;
    else return false;
}
int main(){
    int n,i;
    scanf("%d",&n);
    for(i = 1;i<n+1;i++){
        if(huiwen(i))    printf("%d\n",i);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值