Leetcode-190 Reverse Bits 数字二进制倒置

前端之家收集整理的这篇文章主要介绍了Leetcode-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 as00111001011110000010100101000000).

Follow up:
If this function is called many times,how would you optimize it?

Related problem: Reverse Integer

C++代码实现:

  1. <span style="font-size:12px;color:#000000;">class Solution {
  2. public:
  3. uint32_t reverseBits(uint32_t n) {
  4. uint32_t result = 0;// 表示计算结果
  5. int temp = 0; //计数判断是否移动了32次,因为n左侧大多数数字为0,故不一定要循环移动24 位
  6.  
  7. while (n != 0) {
  8. result = (result << 1) | (n & 1);//每一次上一循环计算的result左移一位,并加上从n取出的该位数字(n & 1)
  9. n >>= 1;
  10. ++ temp;
  11. }
  12. if(temp < 32)
  13. {
  14. result <<= (32 - temp);
  15. }
  16. return result;
  17. }
  18. };</span>


Java实现:在系统上无法运行通过,不知该如何处理无符号int的问题

  1. public class Reverse_Bits {
  2.  
  3. // you need treat n as an unsigned value
  4. public long reverseBits(long n) {
  5. long result = 0;// 表示计算结果
  6. int temp = 0;//
  7. int INT_SIZE = Integer.SIZE;//int类型的size大小
  8. while ((n != 0)&&(temp<=INT_SIZE)) {
  9. result = (result << 1) | (n & 1);
  10. n >>= 1;
  11. ++temp;
  12. }
  13.  
  14. if (temp < INT_SIZE) {
  15. result <<= (INT_SIZE - temp);
  16. }
  17. return result;
  18.  
  19. }
  20.  
  21.  
  22. public static void main(String[] args) {
  23.  
  24. Reverse_Bits reverse_Bits = new Reverse_Bits();
  25.  
  26. System.out.println(reverse_Bits.reverseBits(2147483648L));
  27. }
  28.  
  29. }

修改后实现,使用>>>,其余与C代码相同

  1. public class Solution {
  2. // you need treat n as an unsigned value
  3. public int reverseBits(int n) {
  4. int result = 0;// 表示计算结果
  5. int temp = 0; //计数判断是否移动了32次,因为n左侧大多数数字为0,故不一定要循环移动24 位
  6.  
  7. while (n != 0) {
  8. result = (result << 1) | (n & 1);//每一次上一循环计算的result左移一位,并加上从n取出的该位数字(n & 1)
  9. n >>>= 1;
  10. ++ temp;
  11. }
  12. if(temp < 32)
  13. {
  14. result <<= (32 - temp);
  15. }
  16. return result;
  17.  
  18. }
  19. }


在Java代码中直接书写的数字是int类型的,就是说数字的范围在 -2^31 到 2^31 - 1 这个范围之中,无论将这个数字赋值给什么类型。

直接赋值实参为2147483648时,会出现The literal... of type int is out of range的错误,在数组后加上L,或使用Long.phraseLong()解决问题





猜你在找的设计模式相关文章