gpt4 book ai didi

c++ - 最大回文数(从左到右或从右到左读都是同一个数)

转载 作者:行者123 更新时间:2023-11-30 03:22:37 25 4
gpt4 key购买 nike

任务是找出两个 3 位数字的乘积组成的最大回文数,但我不明白我在哪里犯了错误。

我做了一个循环,得到了两个 3 位数的所有可能的乘积;然后我将乘积转换成一个数组,以便我可以验证它是一个回文数,最后如果它大于最后一个回文数,我将它保存到变量 max_palindrome

这是代码:

#include <iostream>

int number_of_digits(int num){
int digit = 0;
while(num > 0){
digit++;
num /= 10;
}
return digit;
}

int main() {
int max_palindrome = 0;
for(int a = 100; a < 1000; a++){

for(int b = 100; b < 1000; b++){

int product = a * b;
int digits = number_of_digits(product);

// transform number in a vector
int vector_product[digits];
int temporary_num = product;
for(int c = digits-1; c >= 0; c--){
vector_product[c] = temporary_num % 10;
temporary_num /= 10;
}

// verifying that the number is a palindrome
int d = digits-1;
bool palindrome = true;
for(int e = 0; e < digits; e++){
if(vector_product[e] != vector_product[d]){
palindrome = false;
break;
}
d--;
}

if(palindrome && max_palindrome < a){
std::cout<<max_palindrome<<std::endl;
max_palindrome = product;
}
}
}

std::cout<<"The biggest palindrome number from a product of two 3- digits numbers is "<<max_palindrome<<std::endl;

return 0;
}

最佳答案

你的条件是错误的:

if(palindrome && max_palindrome < a){

应该是:

if(palindrome && max_palindrome < product){

如果您只是将数字转换为字符串,您的程序可能会简单得多(可能会稍微慢一些,但您已经通过对数字进行两次循环来浪费 CPU 时间)。

关于c++ - 最大回文数(从左到右或从右到左读都是同一个数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50990833/

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