views:

157

answers:

1

I want to implement a program which tests if a&b==0 . It should return false if the two integers have at least 1 bit in the same location and true if they have 1 bit in different locations.

Here is my code:

import java.util.*;
public class btest{
public static boolean testand(int a,int b){
int i=0;
int k=0;
int m=0;
 while(i<32){
 k= (a>>i) &1;
 m=(b>>i) &1;
   if (k==1 && m==1){
  System.out.println("they have  bit 1   in common at position:"+i);
    return false;
}

i++;
    }

   System.out.println("  a & b  is equal :" + (a &b));
   return true;

}

public static void main(String[]args){

Scanner scnr=new Scanner(System.in);
 int a=scnr.nextInt();
int b=scnr.nextInt();
System.out.println(testand(a,b));


}
}

It works for small values. Will it be correct for large numbers too?

+3  A: 

Yes, it will work at least for numbers up to the 30th bit. The last bit is the sign bit, so you should check that it works for that bit too. You probably have to enter negative numbers in order to get an integer with the 31st bit set.

I reformatted the code, changed some variable names, and changed the while loop to a for loop:

import java.util.*;

public class btest{

  public static boolean TestAnd(int a, int b) {
    for (int i = 0, i < 32, i++) {
      int aBit = (a >> i) & 1;
      int bBit = (b >> i) & 1;
      if (aBit == 1 && bBit == 1) {
        System.out.println("they have  bit 1   in common at position:" + i);
        return false;
      }
    }
    System.out.println("  a & b  is equal :" + (a & b));
    return true;
  }

  public static void main(String[] args) {
    Scanner scnr=new Scanner(System.in);
    int a = scnr.nextInt();
    int b = scnr.nextInt();
    System.out.println(TestAnd(a, b));
  }

}
Guffa