[英]The method returns true if the integer is divisible by 3 and returns false if the integer is not divisible by 3
This is what I have so far; 这是我到目前为止所拥有的; I have to use this main method.
我必须使用这种主要方法。
public class HW4 {
public static boolean isDivisibleByThree(String n) {
int sum = 0;
int value;
for (int k = 0; k < n.length(); k++) {
char ch = n.charAt(k);
value = Character.getNumericValue(ch);
sum = sum*value;
}
return sum*3 == 0;
}
}
It always comes out true and I'm really stuck in this part. 它总是正确的,而我真的被这部分卡住了。 So if you can, can you help me out?
因此,如果可以,您可以帮我吗?
A sum is a cumulative addition (not multiplication). 的总和为累积加法 (未倍增)。
Change this line: 更改此行:
sum = sum * value;
To 至
sum = sum + value;
Or the more brief version: 或更简单的版本:
sum += value;
Two things: 两件事情:
sum = sum * value
? sum = sum * value
? This should probably be sum = sum + value
, or short sum += value
sum = sum + value
或short sum += value
sum * 3 == 0
should probably be sum % 3 == 0
sum * 3 == 0
应该是sum % 3 == 0
If you are required to not use the %
operator, you could alternatively do: 如果需要不使用
%
运算符,则可以选择执行以下操作:
double check = (double)sum / 3.0;
return check == (int)check;
The problem with negative numbers is that the -
gets parsed too, you could sove it by dropping it: 负数的问题是
-
也会被解析,您可以通过删除来解决它:
if (n[0] == '-') {
n = n.substring(1);
}
This drops the sign if it is negative and does nothing otherwise. 如果它为负,则将其删除,否则将不执行任何操作。
Much easier solution: use the mod-function: 更简单的解决方案:使用mod功能:
int number = int.Parse(input);
bool result = (number % 3 == 0);
Unless I'm missing something, you would first use Integer.parseInt(String)
to parse the int
from the String
. 除非我失去了一些东西,你会首先使用
Integer.parseInt(String)
解析int
从String
。 Then you can divide that value by 3 using integer division. 然后,您可以使用整数除法将该值除以3。 Finally, test if that number multiplied by 3 is the original value.
最后,测试该数字乘以3是否为原始值。
int value = Integer.parseInt(n);
int third = value / 3;
return (value == third * 3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.