不是挺简单的吗? 两个相同的数进行&操作还是一样的,所以N-1个数得到的&结果如果和剩下的那个数相同的话再进行&操作还是那个数。 故我们可以把全部数进行&操作,再看看得到的结果是不是在数组中出现过,如果有的话就证明是true。 public class Main { public static void main(String[] args) { int[] a = {5,4,20}; System.out.println(isAndEquation(a));
} public static boolean isAndEquation(int[] a) { int result = a[0]; for (int i = 1; i < a.length; i++) {
result = result & a[i]; } for (int i = 0; i < a.length; i++) { if (result == a[i]) return true; } return false; }
}
public static void main(String[] args) { int b[] = {0,3,7,19,12,32,323,212,31,52}; System.out.println(isAndEqationExist(b)); } public static boolean isAndEqationExist(int a[])
{ int max = 0; for (int i=0;i<a.length;i++) if(a[i]>max)max = a[i]; int count = 0; while(max>0){
max /=2; count++; } int b[] = new int[a.length]; for (int i=0;i<count;i++)
{ int countzero = 0; for (int j=0;j<a.length;j++)
{ if(b[j]!=-1)
{ int bei = (int) Math.pow(2,i); int nn = a[j]&bei; if(nn==0)
{
countzero++; }else if(countzero>0)
b[j] = -1; }else continue; } for (int j=0;j<a.length;j++)
{ if(b[j]!=-1)
{ int bei = (int) Math.pow(2,i); int nn = a[j]&bei; if(nn==0)
{
countzero++; }else if(countzero>0)
b[j] = -1; }else continue; } if(countzero==1)return false; } //搜寻完毕 int index = -1; for (int i=0;i<a.length;i++) if(b[i]==0)index = i; if(index==-1)return false; int sum = 0;boolean fir = true; for (int i=0;i<a.length;i++)
{ if(i!=index)
{ if(fir)
{
sum = sum ^ a[i]; fir = false; }else {
sum &= a[i]; }
}
} if(sum==a[index])return true; return false; }