[英]How to write a program that prints whether a given number is divisible by 3? [on hold]
Write a program that prints whether a given number is divisible by 3. The number can be huge (may contain upto 1000 digits).编写一个程序,打印给定的数字是否能被 3 整除。这个数字可能很大(最多可能包含 1000 位数字)。 (Hint: A number is divisible by 3 if the sum of its digits is divisible by 3.)
(提示:如果一个数字的数字之和可以被 3 整除,则该数字可以被 3 整除。)
As in the question it is given that input can be upto 1000 digits so input will be a huge number.. and a hint is given by me according to mathematical knowledge.. so now if i try to approach through my logic ( given hint ) i should have to take the whole number into array then i have add all the digit.正如在问题中给出的输入最多可以是 1000 位,所以输入将是一个巨大的数字。我根据数学知识给出了一个提示。所以现在如果我尝试通过我的逻辑接近(给出提示)我应该将整个数字放入数组中,然后我添加了所有数字。 But the thing is i couldn't convert the number into a integer array.. what should i do to complete my code According to the way i am approaching?
但问题是我无法将数字转换为 integer 数组。根据我接近的方式,我应该怎么做才能完成我的代码? If you have any new idea or code you can share it..
如果您有任何新的想法或代码,您可以分享它..
` If the input ( integer value): 141414141414141414 ` 如果输入(integer 值):141414141414141414
Output: Divisible by 3 `
I am assuming you are receiving a BigInt.我假设您正在接收 BigInt。
boolean checkMultipleOfThree(BigInt input){
char[] numberCharArray= input.toString().toCharArray();
/*
if original BigInt contains upto 1000 digits,
it means its digit sums will be a maximum of 9000.
So no problem operating with int.
*/
int sum = 0;
for (int i = 0; i < numberCharArray.length; i++) {
sum += Integer.valueOf(numberCharArray[i]);
}
return sum % 3 == 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.