代码有时会返回 Integer.MAX_VALUE。无法弄清楚原因
我正在尝试编写代码来返回组成给定数字所需的最低数量的硬币。我的方法的输入是一组有效的硬币,以及我尝试制造的数字。
public static int change(int[] d, int p) {
int[] tempArray = new int[p + 1]; // tempArray to store set
// of coins forming
// answer
for (int i = 1; i <= p; i++) { // cycling up to the wanted value
int min = Integer.MAX_VALUE; // assigning current minimum number of
// coins
for (int value : d) {// cycling through possible values
if (value <= i) {
if (1 + tempArray[i - value] < min) { // if current value is
// less than min
min = 1 + tempArray[i - value];// assign it
}
}
}
tempArray[i] = min; // assign min value to array of coins
}
return tempArray[p];
}
这适用于大多数情况,但是,当我填写以下内容时:
int[] test = {2,3,4};
System.out.println("answer = " + change(test, 6));
答案应该是 2,对吧?但它打印出来:
-2147483647
我错过了什么?
I am trying to write code to return the lowest number of coins needed to make up a given number. The inputs to my method are an array of valid coins, and the number I try to make.
public static int change(int[] d, int p) {
int[] tempArray = new int[p + 1]; // tempArray to store set
// of coins forming
// answer
for (int i = 1; i <= p; i++) { // cycling up to the wanted value
int min = Integer.MAX_VALUE; // assigning current minimum number of
// coins
for (int value : d) {// cycling through possible values
if (value <= i) {
if (1 + tempArray[i - value] < min) { // if current value is
// less than min
min = 1 + tempArray[i - value];// assign it
}
}
}
tempArray[i] = min; // assign min value to array of coins
}
return tempArray[p];
}
This works for most cases, however, when I fill in the following :
int[] test = {2,3,4};
System.out.println("answer = " + change(test, 6));
The answer should be 2, right? But it prints out :
-2147483647
What have I missed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为,在第一次迭代期间,
tempArray[i] = min;
tempArray[i] 被分配给 MAX,而在后续迭代[s]期间,min = 1 + tempArray[i - value] ;
会尝试将 MAX 加一,这基本上会移动位并形成负对应项。Because, during the first iteration
tempArray[i] = min;
tempArray[i] is assigned to MAX, and during subsequent iteration[s],min = 1 + tempArray[i - value];
would try to increment MAX by one, which basically shifts the bits and forms a negative counterpart.