Java程序检查是否可以使用数组中的所有数字使一个数可以被3整除
给定一个整数数组,任务是找出是否可以使用这些数字的所有数字构造一个整数,使得它可以被 3 整除。如果可以,则打印“是”,如果不能,则打印“否” .
例子:
Input : arr[] = {40, 50, 90}
Output : Yes
We can construct a number which is
divisible by 3, for example 945000.
So the answer is Yes.
Input : arr[] = {1, 4}
Output : No
The only possible numbers are 14 and 41,
but both of them are not divisible by 3,
so the answer is No.
// Java program to find if it is possible
// to make a number divisible by 3 using
// all digits of given array
import java.io.*;
import java.util.*;
class GFG {
public static boolean isPossibleToMakeDivisible(int arr[], int n)
{
// Find remainder of sum when divided by 3
int remainder = 0;
for (int i = 0; i < n; i++)
remainder = (remainder + arr[i]) % 3;
// Return true if remainder is 0.
return (remainder == 0);
}
public static void main(String[] args)
{
int arr[] = { 40, 50, 90 };
int n = 3;
if (isPossibleToMakeDivisible(arr, n))
System.out.print("Yes\n");
else
System.out.print("No\n");
}
}
// Code Contributed by Mohit Gupta_OMG <(0_o)>
输出:
Yes
时间复杂度:O(n)
有关更多详细信息,请参阅有关可能使用数组中的所有数字使一个数被 3 整除的完整文章!