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

标签 c++ string algorithm

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

这是我的代码:

#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/

相关文章:

c++ - 使用 std::string 而不是 char* 不好吗?

c++ - 如果模板别名声明解析为一个新的类型族?

c++ - 使用按位运算符仅查找数组中存在一次的数字

c++ - QVideoWidget 独立。窗口关闭时如何停止视频?

regex - R 列表字符删除

string - 如何在 Go 中通过 rune 迭代字符串?

javascript - 为什么 String([1,2])= ="1,2"而不是 "[1,2]"?

algorithm - 如何将数据分成最小组

c# - 在 .NET 中生成所有整数的随机、非重复序列

javascript - 通过 mapsOrder 数组确定下一张 map