gpt4 book ai didi

c++ - 在 C++ 中使用模数将 "010"和类似数字识别为回文

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:55:56 26 4
gpt4 key购买 nike

第一次发帖!这是我学习“高级 C 和 C++”的第二个学期,非常感谢任何帮助。我已经搜索了尽可能多的 stackoverflow 和一些其他资源,以尝试帮助我理解我在用这些逻辑上无用的代码做什么(或不做什么)。

该程序的目标是识别用户给出的“数字”是否为回文。听起来很简单吧?!呃……好吧,这就是我一直坚持的:

#include <iostream>

using std::cout;
using std::cin;

#include <string>

using std::string;

#include <cstdlib>

int main()
{

//variable declarations
string buffer;

//user input
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);

//looooop
while(buffer != "Q" && buffer !="q")
{
int userNum, length, sum = 0, temp;
userNum = atoi(buffer.c_str());
for(temp = userNum; userNum !=0; userNum=userNum/10)
{
length = userNum % 10;
sum = sum*10+length;
}
if(temp==sum)
cout << temp << " is a palindrome!!\n\n";
else
cout << buffer << " is NOT a palindrome!\n\n";

cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
}
}

当输入“010”或“400”时会出现问题。在这种情况下,“400”本质上是“00400”,两者都应被视为回文。

最佳答案

更好的方法是获取给定数字的尾随零,如下所示:

int noOfTrailingZeros = str.length;
while(str[--noOfTrailingZeros]=='0');
noOfTrailingZeros = str.length - noOfTrailingZeros;

或者整数方式为:

int noOfTrailingZeros = str.length;
while(num%10==0)
{
noOfTrailingZeros++;
num/=10;
}

现在,检查输入字符串是否在数字之前有相同数量的零:

int counterZeros = 0;
while(str[counterZeros++]=='0');

检查这 2 个数字,如果尾随零多于开头的零,则在开头添加那么多并将该字符串传递给回文函数。

关于c++ - 在 C++ 中使用模数将 "010"和类似数字识别为回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19074675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com