public class Solution { public uint reverseBits(uint n) { var list = new List<uint>();//逆序的二进制列表,list[0]是最低位 while (n != 0) { var cur = n % 2; list.Add(cur); n = n / 2; } var addzero = 32 - list.Count; for (int i = 0; i < addzero; i++)//补充到32位 { list.Add(0); } list.Reverse(); uint sum = 0; for (int i = 0; i < list.Count; i++) { var cur = list[i]; sum += cur * ((uint)(Math.Pow(2, i))); } return sum; } }
https://leetcode.com/problems/reverse-bits/#/description
补充一个python的实现:
1 class Solution: 2 def reverseBits(self, n: int) -> int: 3 l = [0] * 32#用于存储n的二进制表示 4 pos = 0 5 while n != 0: 6 cur = n % 2 7 l[pos] = cur 8 pos += 1 9 n = n // 2 10 l.reverse() 11 12 ret = 0 13 for i in range(32): 14 cur = l[i] 15 ret += cur * pow(2,i) 16 return ret