[LeetCode]--190. Reverse Bits(不是很懂的位运算)

    xiaoxiao2026-05-12  1

    补充知识,Java的位运算(bitwise operators)

    Reverse bits of a given 32 bits unsigned integer.

    For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

    Follow up: If this function is called many times, how would you optimize it?

    Related problem: Reverse Integer

    Credits: Special thanks to @ts for adding this problem and creating all test cases.

    public int reverseBits(int n) { int reversed = 0; for (int i = 0; i < 32; i++) { reversed = (reversed << 1) | (n & 1); n = (n >> 1); } return reversed; }

    懂了按位运算这个程序很容易看懂,但是很难想到。

    我的思路是这样的。先转到32位二进制的String,然后交换之后又转到int。我觉得思路是正确的,但是有一些问题,不能通过。

    public int reverseBits(int n) { String str = intToBinary(n); char[] strs = str.toCharArray(); char temp = ' '; int i = 0, j = strs.length - 1; while (i < j) { temp = strs[i]; strs[i] = strs[j]; strs[j] = temp; i++; j--; } str = String.valueOf(strs); return binaryToInt(str); } public String intToBinary(int n) { String str = ""; while (n != 0) { str = n % 2 + str; n = n / 2; } int len = str.length(); for (int i = 0; i < 32 - len; i++) { str = "0" + str; } return str; } public int binaryToInt(String str) { int len = str.length() - 1; double sum = 0; for (int i = 0; i <= len; i++) { sum = sum + charToInt(str.charAt(i)) * Math.pow(2, len - i); } System.out.println(sum + "---" + Integer.MAX_VALUE); System.out.println(2147483647 + 1); return 0; } public int charToInt(char c) { if (c == '0') return 0; else return 1; }

    第一个问题在于int会超出范围的。

    最新回复(0)