C 中的回文数程序
Palindrome Number Program in C
我正在尝试制作一个 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
,因此变量c
、d
和e
的值是相同的。因此,取一个模数后,您也应该将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);
}
}
只需遵循简单的数字提取算法即可完成所有程序,例如回文,反向,数字总和。可以轻松解决
相关文章:
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- 程序以查找给定字符串中回文的子字符串的数量
- 如何创建一个程序来标识最长的子字符串回文,而不考虑字母大小写
- 测试回文时程序不会继续运行 (C++)
- 回文程序和条件跳转或移动取决于未初始化的值
- C 中的回文数程序
- 使用 C++ 的回文程序的不需要的输出
- 内联程序集 - 检查单词是否为回文
- 使用数组的 C++ 回文程序
- 回文程序中非常奇怪的问题
- C++回文程序
- 堆栈和队列回文程序
- 使用堆栈和队列的回文程序
- 在制作回文程序 C++ 时遇到困难
- C++回文创建者递归程序
- 字符串回文程序不会忽略案例
- 需要修改堆栈/链表程序以确定单词是否为回文
- 我的回文程序给出了一个例外
- 回文子字符串程序无法运行