作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
任务是找出两个 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/
目前我正在使用 [self presentModalViewController :newVC animated:YES] 。我想从左/右/顶部/底部呈现带有推送效果的 newViewcontroll
我正在尝试实现“带有上一个和下一个的部分幻灯片”。这些部分的标记如下: Section 1 Section 2 Section 3 Prev Next 除具有 acti
我的问题与此处提出的问题几乎相同:question 不同的是,我想从右边切换第 2 位和第 4 位数字,而不是像另一个问题中那样从左边切换。所以在我的例子中最右边的数字是 1。示例:283926.67
我是一名优秀的程序员,十分优秀!