//判斷一個整數是否是2的N次方 private boolean is2N(int num) { return (num & (num - 1)) == 0; } //判斷一個正整數是奇數仍是偶數,便可不是被2整除 private boolean isEvenNumber(int num) { return (num & 1) == 0; }
338:https://leetcode-cn.com/probl...java
給定一個非負整數 num。計算其二進制數中的 1 的數目。數組
private int getBit1Count(int number) { int mask = 1; int count = 0; for (int i = 0; i < 32; i++) { if ((number & mask) != 0) { count += 1; } mask <<= 1; } return count; }
136:https://leetcode-cn.com/probl...code
給定一個非空整數數組,除了某個元素只出現一次之外,其他每一個元素均出現兩次。找出那個只出現了一次的元素。leetcode
1:rem
public int selectSinlgeNumber(int[] array) { // a^a = 0, 0^x = x // a^b^a = a^a^b =b int a = 0; for (int i = 0; i < array.length; i++) { a ^= array[i]; Log.i(TAG, "selectSinlgeNumber: " + a); } return a; }
2:get
public int selectSinlgeNumber1(int[] array) { HashSet<Integer> hashSet = new HashSet<>(); for (int i = 0; i < array.length; i++) { if (!hashSet.add(array[i])) { hashSet.remove(array[i]); } } Integer[] array1 = (Integer[]) hashSet.toArray(); return array1[0]; }
260:https://leetcode-cn.com/probl...hash
給定一個整數數組 nums
,其中剛好有兩個元素只出現一次,其他全部元素均出現兩次。 找出只出現一次的那兩個元素。it
public int[] selectTheSinlgeNumbers(int[] array) { int a = 0; for (int i = 0; i < array.length; i++) { a ^= array[i]; } int mask = a & -a; int[] b = new int[2]; for (int j = 0; j < array.length; j++) { if ((mask & array[j]) == 0) { b[0] ^= array[j]; } else { b[1] ^= array[j]; } } return b; }