190. Reverse Bits
一、題目
Reverse bits of a given 32 bits unsigned integer.
Note:
- Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
- In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer
-3and the output represents the signed integer-1073741825.
Example 1:
Input: n = 00000010100101000001111010011100 Output: 964176192 (00111001011110000010100101000000) Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: n = 11111111111111111111111111111101 Output: 3221225471 (10111111111111111111111111111111) Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
Constraints:
- The input must be a binary string of length
32
Follow up: If this function is called many times, how would you optimize it?
二、程式作法
/*寫法二*/
public class Solution
{
public uint reverseBits(uint n)
{
uint result = 0;
uint[] a = new uint[32];
int counter = 0;
while (n > 0)
{
a[counter] = n % 2;
n /= 2;
counter++;
}
counter = 0;
while (counter < a.Length / 2)
{
uint temp = a[counter];
a[counter] = a[a.Length - 1 - counter];
a[a.Length - 1 - counter] = temp;
counter++;
}
counter = 0;
while (counter < a.Length)
{
result += (uint)Math.Pow(2, counter) * a[counter];
counter++;
}
return result;
}
}
/*寫法一*/
/*
public class Solution
{
public uint reverseBits(uint n)
{
string s = Convert.ToString(n, 2);
char[] c = s.ToCharArray();//index 越大,權重越低位,反之,index 在起始為零時,為最大權重
char[] c32 = new char[32];
for (int i = 0; i < c32.Length; i++)
{
if (i + c.Length < c32.Length)
c32[i] = '0';
else
c32[i] = c[i - (c32.Length - c.Length)];
}
for (int i = 0; i < c32.Length / 2; i++)
{
char temp = c32[i];
c32[i] = c32[c32.Length - 1 - i];
c32[c32.Length - 1 - i] = temp;
}
string s32 = new string(c32);
return Convert.ToUInt32(s32, 2);
}
}
*/
三、思路筆記
我想法為將該無號整數先轉成陣列,然後再做元素調換,最後轉回無號整數回傳答案。