2010-06-21 60 views
-3

我想實現一個程序來測試是否& b == 0。如果兩個整數在同一位置至少有1位,它應該返回false,如果它們在不同位置有1位,則返回true。測試是否a&b == 0

這裏是我的代碼:

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)); 
    } 
} 

它適用於小的值。這對大數字是否正確?

+11

你爲什麼不只是使用'A&B'? – 2010-06-21 05:22:04

+0

如果您希望人們閱讀您的代碼,那麼您可以先嚐試格式化它,這會有所幫助。 – bdonlan 2010-06-21 05:23:00

+0

是的。格式化它,並刪除任何無用的空格,如果可能,爲所有變量選擇有意義的名稱。 – MatrixFrog 2010-06-21 05:39:11

回答

3

是的,它至少可以用於第30位的數字。最後一位是符號位,所以您應該檢查它是否適用於該位。您可能必須輸入負數才能獲得第31位的整數。

我重新格式化代碼,改變了一些變量名,並改變了while循環到for循環:

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)); 
    } 

}