简体   繁体   English

将计算值存储到数组中

[英]Storing computed values to an array

I'm trying some online problems. 我正在尝试一些在线问题。 I programmed how to solve the greatest palindrome product of 2 two-digit numbers. 我编写了如何解决2个两位数字的最大回文产品。 For example 91*99=9009. 例如91 * 99 = 9009。 I managed to do it by using the recursive function but I wonder how can i do it using arrays like this one? 我设法通过使用递归函数来做到这一点,但我想知道如何使用像这样的数组呢?

product[0]=9;
product[1]=0;
product[2]=0;
product[3]=9;

or if the computed product is 969; 或者如果计算的产品是969;

product[0]=9;
product[1]=6;
product[2]=9;

Then I will output it starting from the last index to the first index then test if its equal to the original number. 然后我将从最后一个索引开始输出到第一个索引然后测试它是否等于原始数字。

EDIT: My question is, how can i store the computed product to an array? 编辑:我的问题是,我如何将计算产品存储到数组?

从整数乘积创建一个新的String

There's no reason to solve that Project Euler problem using arrays. 没有理由使用数组解决Project Euler问题。 But if you're fixated on it, then there is a simple algorithm to convert an array of digits into a number. 但是如果你注意它,那么有一个简单的算法可以将数字数组转换为数字。 Just do this: 这样做:

int number = 0;
int number_2 = 0;

//going forwards:
for (int i = 0; i < array.length; i++)
{
    number = number * 10 + array[i];
}

//going backwards:
for (int i = array.length - 1; i >= 0; i--)
{
    number_2 = number_2 * 10 + array[i];
}

if (number == number_2)
{
    //you have a palindrome
}

It's not the most efficient method, I know (@Nandkumar's is faster), but it's really really simple, that's what I was aiming for. 这不是最有效的方法,我知道(@ Nandkumar的速度更快),但它真的很简单,这就是我的目标。

I won't writ you code, because it looks like an assignment, but I'll give you a hint. 我不会写你的代码,因为它看起来像一个任务,但我会给你一个提示。

Convert the int into a string first. 首先将int转换为字符串。

Characters in a string are very much like arrays, so it'll be easy to convert the string into an array. 字符串中的字符与数组非常相似,因此将字符串转换为数组很容易。

要将数字转换为数组,您可以尝试这个...

Char [] product = String.valueOf("969").toCharArray();

Provide your product to String.valueOf(int) , it will be converted to string and then convert it into array using String.toCharArray() like 将您的产品提供给String.valueOf(int) ,它将被转换为字符串,然后使用String.toCharArray()将其转换为数组

boolean palindrome = true;
int product = 9009; // or any calculated number
char str[] = String.valueOf(product).toCharArray();

for(int i=0,j=str.length-1; i!=j ;i++,j--) {
    if(str[i] == str[j]){
        continue;
    } else {
        palindrome = false;
        break;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM