C程序,以查找数字是否是回文

时间:2015-11-19 13:34:45

标签: c palindrome

我做了一个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;
}

4 个答案:

答案 0 :(得分:1)

^是xor运算符。

为了提高权力,您需要加入math.h并致电pow

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

答案 1 :(得分:1)

这个算法就像人类思维一样简单,并且可以正常运行

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

答案 2 :(得分: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);
}

答案 3 :(得分:0)

这样的循环可能会:

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)...