|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=190 lang=java |
| 3 | + * |
| 4 | + * [190] Reverse Bits |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/reverse-bits/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Easy (30.22%) |
| 10 | + * Total Accepted: 176.4K |
| 11 | + * Total Submissions: 572K |
| 12 | + * Testcase Example: '00000010100101000001111010011100' |
| 13 | + * |
| 14 | + * Reverse bits of a given 32 bits unsigned integer. |
| 15 | + * |
| 16 | + * |
| 17 | + * |
| 18 | + * Example 1: |
| 19 | + * |
| 20 | + * |
| 21 | + * Input: 00000010100101000001111010011100 |
| 22 | + * Output: 00111001011110000010100101000000 |
| 23 | + * Explanation: The input binary string 00000010100101000001111010011100 |
| 24 | + * represents the unsigned integer 43261596, so return 964176192 which its |
| 25 | + * binary representation is 00111001011110000010100101000000. |
| 26 | + * |
| 27 | + * |
| 28 | + * Example 2: |
| 29 | + * |
| 30 | + * |
| 31 | + * Input: 11111111111111111111111111111101 |
| 32 | + * Output: 10111111111111111111111111111111 |
| 33 | + * Explanation: The input binary string 11111111111111111111111111111101 |
| 34 | + * represents the unsigned integer 4294967293, so return 3221225471 which its |
| 35 | + * binary representation is 10101111110010110010011101101001. |
| 36 | + * |
| 37 | + * |
| 38 | + * |
| 39 | + * Note: |
| 40 | + * |
| 41 | + * |
| 42 | + * Note that in some languages such as Java, there is no unsigned integer type. |
| 43 | + * In this case, both input and output will be given as signed integer type and |
| 44 | + * should not affect your implementation, as the internal binary representation |
| 45 | + * of the integer is the same whether it is signed or unsigned. |
| 46 | + * In Java, the compiler represents the signed integers using 2's complement |
| 47 | + * notation. Therefore, in Example 2 above the input represents the signed |
| 48 | + * integer -3 and the output represents the signed integer -1073741825. |
| 49 | + * |
| 50 | + * |
| 51 | + * |
| 52 | + * |
| 53 | + * Follow up: |
| 54 | + * |
| 55 | + * If this function is called many times, how would you optimize it? |
| 56 | + * |
| 57 | + */ |
| 58 | +public class Solution { |
| 59 | + // you need treat n as an unsigned value |
| 60 | + public int reverseBits(int n) { |
| 61 | + int result = 0; |
| 62 | + for (int i = 0; i < 32; i++) { |
| 63 | + result = (result << 1) + (n & 1); |
| 64 | + n = n >>> 1; |
| 65 | + } |
| 66 | + return result; |
| 67 | + } |
| 68 | +} |
| 69 | + |
0 commit comments