190. Reverse Bits
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?
题目含义:反转一个32位无符号的整数。
思路:设这个数为k,用一个初值为0的数r保存反转后的结果,用1对k进行求与,其结果与r进行相加,再对k向右进行一位移位,对r向左进行一位移位。值到k的最后一位处理完。
1 public int reverseBits(int n) { 2 int res = 0; 3 // for (int i = 0; i < 32; ++i) { 4 // res |= ((n >> i) & 1) << (31 - i); 5 // } 6 // return res; 7 for(int i = 0; i < 32; i++) 8 { 9 res = (res << 1) + (n & 1); 10 n = n >> 1; 11 } 12 return res; 13 }
相关题目:7. Reverse Integer
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步