所以这个程序基本上是通过一个1000位的字符串(在这个例子中缩短了)并拉出构成最高产品的5位数字。我能够输出构成最高产品的数字之和,但不能输出实际数字的总和。
public class ThousandDigitString
{
public static void main(String[] args){
String num = "73167176531";
int product = 0;
int product2 = 0;
for(int i = 0; i < num.length()-4; i++)
{
product2 = Character.getNumericValue(num.charAt(i))* Character.getNumericValue(num.charAt(i+1)) * Character.getNumericValue(num.charAt(i+2)) *
Character.getNumericValue(num.charAt(i+3))* Character.getNumericValue(num.charAt(i+4));;
if(product2 > product)
{
product=product2;
}
}
System.out.println(product);
}
}
答案 0 :(得分:2)
int startingIndex = 0;
for(int i = 0; i < num.length()-4; i++)
{
product2 = Character.getNumericValue(num.charAt(i))* Character.getNumericValue(num.charAt(i+1)) * Character.getNumericValue(num.charAt(i+2)) *
Character.getNumericValue(num.charAt(i+3))* Character.getNumericValue(num.charAt(i+4));;
if(product2 > product)
{
product=product2;
startingIndex = i;
}
}
System.out.println(product);
// retrieve digits from string at startingIndex to startingIndex + 4
答案 1 :(得分:1)
您可以将单个字符保存到数组或ArrayList中,然后检查product2&gt;产品保存阵列
例如:
public class ThousandDigitString
{
public static void main(String[] args){
String num = "73167176531";
int product = 0;
int product2 = 0;
int index = 0;
int[] numbers = new int[5];
for(int i = 0; i < num.length()-4; i++)
{
product2 = Character.getNumericValue(num.charAt(i))* Character.getNumericValue(num.charAt(i+1)) * Character.getNumericValue(num.charAt(i+2)) *
Character.getNumericValue(num.charAt(i+3))* Character.getNumericValue(num.charAt(i+4));;
if(product2 > product)
{
product=product2;
index = i;
}
}
numbers[0] = Character.getNumericValue(num.charAt(index));
numbers[1] = Character.getNumericValue(num.charAt(index+1));
numbers[2] = Character.getNumericValue(num.charAt(index+2));
numbers[3] = Character.getNumericValue(num.charAt(index+3));
numbers[4] = Character.getNumericValue(num.charAt(index+4));
System.out.println(Arrays.toString(numbers));
System.out.println(product);
}
}
答案 2 :(得分:0)
当您将product2替换为产品时,您可以存储构成产品的5位数字,然后将它们打印出来。可以是5个新变量,也可以是数组。
public class ThousandDigitString
{
public static void main(String[] args){
String num = "73167176531";
int product = 0;
int product2 = 0;
int i1 = 0;
int i2 = 0;
int i3 = 0;
int i4 = 0;
int i5 = 0;
for(int i = 0; i < num.length()-4; i++)
{
product2 = Character.getNumericValue(num.charAt(i))* Character.getNumericValue(num.charAt(i+1)) * Character.getNumericValue(num.charAt(i+2)) *
Character.getNumericValue(num.charAt(i+3))* Character.getNumericValue(num.charAt(i+4));;
if(product2 > product)
{
int i1 = num.charAt(i);
int i2 = num.charAt(i+1);
int i3 = num.charAt(i+2);
int i4 = num.charAt(i+3);
int i5 = num.charAt(i+4);
}
}
System.out.println(product);
System.out.println(i1);
System.out.println(i2);
System.out.println(i3);
System.out.println(i4);
System.out.println(i5);
}
}
如果您熟悉它们,阵列将比单个变量更整洁。
答案 3 :(得分:0)
我认为这比制作它容易得多。将字符串解析为数组维护找出最大的5位数。你实际上不需要在循环内相乘。
一旦找到前5位数字。这些是你想要的数字。将它们转换为int并将它们相乘,即可得到产品。