publicclassSolution {// you need treat n as an unsigned valuepublicintreverseBits(int n) {int rev =0;for(int i=0; i<32&& n!=0; i++){ rev |=(n&1)<<(31-i); n >>>=1; }return rev; }}
publicclassSolution {privatestaticfinalint M1 =0x55555555; // 01010101010101010101010101010101privatestaticfinalint M2 =0x33333333; // 00110011001100110011001100110011privatestaticfinalint M4 =0x0f0f0f0f; // 00001111000011110000111100001111privatestaticfinalint M8 =0x00ff00ff; // 00000000111111110000000011111111publicintreverseBits(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的个数
publicstaticintbitCount(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的值
publicstaticinthighestOneBit(int i) {// 先把i最高位1以下的所有位都变成1。折半法 i |= (i >>1); i |= (i >>2); i |= (i >>4); i |= (i >>8); i |= (i >>16);//用移位运算得到最高位的ireturn i - (i >>>1); }
Integer.lowestOneBit(3) ---最低位的1的值
publicstaticintlowestOneBit(int i) {// HD, Section 2-1return i &-i; }
Integer.numberOfLeadingZeros(3) ---前面0的个数
publicstaticintnumberOfLeadingZeros(int i) {// HD, Figure 5-6if (i ==0)return32;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的个数
publicstaticintnumberOfTrailingZeros(int i) {// HD, Figure 5-14int y;if (i ==0) return32;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
List<Character> letters =newArrayList<>(List.of('A','B','C','D','E'));Collections.shuffle(letters);System.out.println(letters); // 输出可能为 [C, A, B, E, D]
List<Integer> sortedNumbers =newArrayList<>(List.of(1,2,3,4,5,6,7,8,9)); //必须是排序数组int index =Collections.binarySearch(sortedNumbers,5);System.out.println("Index of 5: "+ index); // 输出 Index of 5: 4