java解惑之奇數判斷

來源:互聯網
上載者:User

static boolean isOdd(int i) {<br />return (i % 2 == 1);<br />}</p><p>static boolean isOdd2(int i) {<br />return (i % 2 != 0);<br />}</p><p>static boolean isOdd3(int i) {<br />return (i & 1) != 0;<br />}

貌似以上三個函數在判斷一個整數是否為奇數的情況下都是正確的,但是我們測試一下

static int a = 5;<br />static int b = 4;<br />static int c = -6;<br />static int d = -3;</p><p>System.out.println(a + "is odd,true or false?" + isOdd(a));<br />System.out.println(b + "is odd,true or false?" + isOdd(b));<br />System.out.println(c + "is odd,true or false?" + isOdd(c));<br />System.out.println(d + "is odd,true or false?" + isOdd(d));<br />System.out.println("***********************************");<br />System.out.println(a + "is odd,true or false?" + isOdd2(a));<br />System.out.println(b + "is odd,true or false?" + isOdd2(b));<br />System.out.println(c + "is odd,true or false?" + isOdd2(c));<br />System.out.println(d + "is odd,true or false?" + isOdd2(d));

 

程式列印結果:

5is odd,true or false?true<br />4is odd,true or false?false<br />-6is odd,true or false?false<br />-3is odd,true or false?false<br />***********************************<br />5is odd,true or false?true<br />4is odd,true or false?false<br />-6is odd,true or false?false<br />-3is odd,true or false?true

 

 

 說明:

第一個函數 isOdd()在四分之一的時間裡是返回錯誤結果的,在參數為負數的情況下,i %2 == 0總是返回FALSE的,這事因為對%取餘運算 其結果的符號總是和左運算元的符號相同的,

而第二個函數修正了第一個函數的不足之處 令其結果和1去比較,是完全正確的

第三個函數是效率最高的,一個數是否為奇數 ,只須判斷它的二進位位是否為1即可,

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.