public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int rev =0;
for(int i=0; i<32 && n!=0; i++){
rev |=(n&1)<<(31-i);
n >>>=1;
}
return rev;
}
}
public class Solution {
private static final int M1 = 0x55555555; // 01010101010101010101010101010101
private static final int M2 = 0x33333333; // 00110011001100110011001100110011
private static final int M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
private static final int M8 = 0x00ff00ff; // 00000000111111110000000011111111
public int reverseBits(int n) {
//交换不同的位置
n = n >>> 1 & M1 | (n & M1) << 1;
n = n >>> 2 & M2 | (n & M2) << 2;
n = n >>> 4 & M4 | (n & M4) << 4;
n = n >>> 8 & M8 | (n & M8) << 8;
return n >>> 16 | n << 16;
}
}
Integer.bitCount(122) --统计int中1的个数
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
Integer.highestOneBit(123) ---最高位的1的值
public static int highestOneBit(int i) {
// 先把i最高位1以下的所有位都变成1。折半法
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
//用移位运算得到最高位的i
return i - (i >>> 1);
}
Integer.lowestOneBit(3) ---最低位的1的值
public static int lowestOneBit(int i) {
// HD, Section 2-1
return i & -i;
}
Integer.numberOfLeadingZeros(3) ---前面0的个数
public static int numberOfLeadingZeros(int i) {
// HD, Figure 5-6
if (i == 0)
return 32;
int n = 1;
//折半法
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
//如果前面条件都不满足
n -= i >>> 31;
return n;
}
Integer.numberOfTrailingZeros(3) ---后面0的个数
public static int numberOfTrailingZeros(int i) {
// HD, Figure 5-14
int y;
if (i == 0) return 32;
int n = 31;
y = i <<16; if (y != 0) { n = n -16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
return n - ((i << 1) >>> 31);
}
java.util.HashMap
map.getOrDefault(a,b);
map.remove(key);
map.containsKey(key)
map.values()
java.util.HashSet
把List转成Set
List list = Arrays.asList("apple", "orange", "banana");
Set set = new HashSet<>(list);
List list = Arrays.asList("apple", "orange", "banana");
Set set = new HashSet<>();
set.addAll(list);
java.util.List
list.add("apple"); // 在末尾添加元素
list.add(0, "banana");
list.remove("apple"); // 删除元素"apple"
list.remove(1);
list.clear();
//list转数组:
list.toArray(new int[0])
list.toArray(new int[0][2])
//list to数组字符串:
list.toString() [1, 2]
Array
[]:
int[] array = {1, 2, 3, 4, 5};
int length = array.length;
java.util.Arrays
List wordList = Arrays.asList(s.split("\\s+")); ----数组变成list
Stack<Integer> stack = new Stack<>();
stack.push(1);
int top = stack.peek();
int poppedElement = stack.pop();
PriorityQueue<Float> minHeap = new PriorityQueue<>(k);