Blind 75
Reverse Bits
- Problem
- LC 190
- Category
- Binary
- File
- blind75_LC190ReverseBits.java
- Path
- pkg5leetcode/blind75/blind75_LC190ReverseBits.java
- Package
- pkg5leetcode.blind75
- Command
- java pkg5leetcode/blind75/blind75_LC190ReverseBits.java
- Approach
- Extract LSB, build result left-to-right over 32 iterations.
- Complexity
- Time O(32), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.blind75;2 3/*4 * Reverse Bits | LC 1905 * APPROACH: Extract LSB, build result left-to-right over 32 iterations.6 * COMPLEXITY: Time O(32), Space O(1)7 */8public class blind75_LC190ReverseBits {9 static int reverseBits(int n) {10 int res = 0;11 for (int i = 0; i < 32; i++) {12 res = (res << 1) | (n & 1);13 n >>>= 1;14 }15 return res;16 }17 18 public static void main(String[] args) {19 check(reverseBits(43261596) == 964176192, "case1");20 check(reverseBits(0) == 0, "case2");21 System.out.println("all tests passed");22 }23 24 static void check(boolean cond, String name) {25 if (!cond) throw new AssertionError("FAILED: " + name);26 System.out.println(" PASS " + name);27 }28}