gpt4 book ai didi

c++ - 从两个 N 位数字的乘积中找出回文

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:29:28 24 4
gpt4 key购买 nike

我的代码可以编译,但似乎永远找不到答案。这很奇怪,因为我看过几秒钟内完成的几乎相同的代码。

这是我的代码:

#include <iostream>

#include <sstream>

int main()
{
for(int i = 999; i >=100; i--)
{
for(int j=999; j>=100;j--)
{
int num = (i*j);
std::string number;
std::string temp;
std::string reversed;
std::stringstream out;
out << num;
number = out.str();
temp = number;
std::reverse(temp.begin(),temp.end());
if( temp == number)
{
std::cout << number << std::endl;
}

}
}



std::cin.get();
return 0;
}

现在这是我知道可以运行并且运行速度非常快的代码。我看不出我们在做什么不同。

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
// Count down from largest to smallest, so first palindrome found is the largest

unsigned biggestProduct = 0;

for(unsigned n1=999; n1>=100; --n1) {
for(unsigned n2=999; n2>=100; --n2) {
unsigned thisProduct = n1 * n2;

if(thisProduct > biggestProduct) {
stringstream strmProduct;
string strProductReverse;

strmProduct << n1 * n2;

strProductReverse = strmProduct.str();
reverse(strProductReverse.begin(), strProductReverse.end());

if(strmProduct.str() == strProductReverse)
biggestProduct = thisProduct;
}
}
}

cout << biggestProduct << endl;
cin.get();

return 0;

}

最佳答案

for(int i = 999; i <=100; i--)

这会运行吗(j 也一样)? :)

for(int i = 999; i >=100; i--)

关于c++ - 从两个 N 位数字的乘积中找出回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7098690/

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