繁体   English   中英

用C程序查找数字是否为回文

[英]C program to find if a number is palindrome or not

我编写了一个C程序来检查数字是否为回文。 我使用了以下代码,但它显示的数字如12321为非回文。 您能否在下面的程序中向我解释错误?

#include <stdio.h>
int main()
{
    int i, x, n, c, j;
    int d=0;
    printf ("enter total digits in number: ");
    scanf ("%d", &i);
    printf ("\nenter number: ");
    scanf ("%d", &n);
    j=n;
    for (x=1; x<=i; x++)
    {
       c= j%10;
       d=c*(10^(i-x))+d;
       j=(j-c)/10;
    }
    if (d==n)
    {
        printf ("\npalindrome");
    }
    else
    {
        printf ("\nnon palindrome");
    }
    return 0;
}

^是xor运算符。

为了提高功能,您需要包括math.h并调用pow

d = (c * pow(10, i - x)) + d;

这种算法就像人类的思维一样简单,并且有效

#include <stdio.h>


int main() {
    int i=0,n,ok=1;
    char buff[20];


    printf("Enter an integer: ");
    scanf("%d", &n); // i am ommiting error checking

    n=sprintf(buff,"%d",n); //convert it to string, and getting the len in result
    if(n<2) return 0;

    i=n/2;
    n--;
    while(i && ok) {
        i--;
        //printf("%c == %c %s\n", buff[i],buff[n-i],(buff[i]==buff[n-i])?"true":"false");
        ok &= (buff[i]==buff[n-i]);

    }

    printf("%s is %spalindrome\n",buff, ok?"":"not ");
    return 0;
}
// Yet another way to check for palindrome.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    int n, rn, tn;
    printf("Enter an integer: ");
    scanf("%d", &n);    

    // reverse the number by repeatedly extracting last digit, add to the  
    // previously computed partial reverse times 10, and keep dropping  
    // last digit by dividing by 10  
    for (rn = 0, tn = n; tn; tn /= 10) rn = rn * 10 + tn % 10;
    if (rn == n) printf("%d is palindrome\n", n);
    else printf("%d is not palindrome\n", n);
}

这样的循环可能会做:

int src;     // user input
int n;       // no of digits
int res = 0;
int tmp;     // copy of src

// .... read the input: n and src ....

tmp = src;
for(int i = 0; i < n; i ++)
{
    int digit = tmp % 10;  // extract the rightmost digit
    tmp /= 10;             // and remove it from source
    res = 10*res + digit;  // apend it to the result
}

// ...and test if(res == src)...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM