1/ About the modulus:
對于求余運算需要注意,當被除數是一個負數的時候,余數永遠都是負的。所以你判斷是否為奇數的條件不能是:x % 2 == 1,而是 x % 2 != 0。
2/ 如何提取出一個數的個、十...位(從低到高)
public Class Example { public static void main(String[] args) { int x = Integer.parseInt(args[0]); while (x != 0) { int digit = Math.abs(x % 10); // 如果不加math.abs的話如果被余數是負的,結果都是負數來的 System.out.PRintln(digit); x = x / 10; } }}3/ Keep in mind of overflow problem如果int到了最大的2^30次方,不能再乘以2(右移一位)了。強行再右移的話,會瞬間變為最小的int,值是-2^31次方。下面的程序就有這樣的問題:
public class Example { public static void main(String[] args) { int x = Integer.parseInt(args[0]); boolean answer = false; int p = 1; while (p <= x) { System.out.println("Testing" + p); if (p == x) { answer = true; } p = p * 2; } System.out.println(answer); }}上述程序嘗試測試一個數是否是2的倍數。然而,當所給的參數大于int的2^31 - 1時候,會產生overflow問題,程序進入死循環。4/
新聞熱點
疑難解答