C 中的回文数程序

Palindrome Number Program in C

本文关键字:程序 回文      更新时间:2023-10-16

我正在尝试制作一个 C 程序来确定五位数整数是否是回文。我正在努力的部分不是使用循环,因为我知道如何使用循环来做到这一点。但是,我应该在没有一个的情况下执行此操作,而是使用嵌套的 if else 语句。我已经想出了如何反转 3 位数字而不是 5 位数字,然后从那里继续。这是我到目前为止所拥有的。我只是在学习,所以也有点难。

#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
    int a, b, c, d, e , num, reversed;
    cout << "n Enter a five digit number";
    cin >> num;
    a = num / 100;
    b = (num % 100) / 10;
    c = num % 10;
    d = num % 10;
    e = num % 10;
    reversed = 100 * c + 10 * b + a;
    cout << " " << reversed;
    return 0;
}

同样,我无法让它适用于 5 位数字,但我假设之后使用 if else 语句我可以将反转和原始数字与 % 联系起来,看看它是否是回文。

num = numInput;
a = num % 10; num /= 10;
b = num % 10; num /= 10;
c = num % 10; num /= 10;
d = num % 10; num /= 10;
e = num % 10;
reversed = ((((( a * 10) + b ) * 10 + c ) * 10 + d ) * 10 ) + e;
isPalindrome = ( (numInput == reversed) ? 1 : 0 );

或者,如果您想要代码的一些"对称性"(绝对不需要(:

rev = 0;
rev += a; rev *= 10;
rev += b; rev *= 10;
rev += c; rev *= 10;
rev += d; rev *= 10;
rev += e;

但是使用循环要好得多。

这是因为在这些语句中没有对变量num进行任何更改:

c = num % 10;
d = num % 10;
e = num % 10;

您根本不更新num,因此变量cde的值是相同的。因此,取一个模数后,您也应该将num变量除以 10 以向后移动一位数。

a = num % 10;  // get the last digit of num
num /= 10;     // update the last digit (num reduced by 1 digit, '12345' will become '1234')
b = num % 10;
num /= 10;
c = num % 10;
num /= 10;
d = num % 10;
num /= 10;
e = num % 10;
cout << a << b << c << d << e << endl;

由于您只在代码中打印反转的数字,因此无需再次构造反转的数字。但如果你这样做,一旦你有了数字,它就变得微不足道了。

reversed = 10000 * a + 1000 * b + 100 * c + 10 * d + e;

我相信你可以从这里开始检查这个数字是否是回文(isPalindrome = (reversed == num)(。

如果您希望解决方案智能,则必须使用循环。如果您希望解决方案是通用的,您应该使用指针(通过一些更改,您可以将回文检查适应任何单词/短语,因为回文不仅仅是数字(。像这样:

#include <iostream>
#include <sstream>
#include <cstring>
using namespace std;
int main()
{
    unsigned long long int num;
    cout << "n Enter integer:n";
    cin >> num;
    std::stringstream ss;
    ss << num;
    const char * itss = ss.str().c_str(); 
    const char * ites = itss + strlen(itss) - 1;
    int is_palindrome = 1;
    while (itss <= ites) {
     if (*itss != *ites) {
      is_palindrome = 0;
      break;
     }
     itss++;
     ites--;
    }
    cout << "your number is " << (is_palindrome ? "a palindrome" : "NOT a palindrome") << "n";
    return 0;
}
int main(){
  int n,m,d,s=0;
  scanf("%d",&n);
  m=n;
  while(m!=0){
    d=m%10;
    s=(s*10)+d;
    m=m/10;
  }
  if(r==n){
    printf("%d is palindrome",n);
  }else{
    printf ("%d is not palindrome",n);
  }
}

只需遵循简单的数字提取算法即可完成所有程序,例如回文,反向,数字总和。可以轻松解决