zoukankan      html  css  js  c++  java
  • leetcode 190. Reverse Bits

    题目内容

    Reverse bits of a given 32 bits unsigned integer.

    Example:
    Input: 00000010100101000001111010011100
    Output: 00111001011110000010100101000000
    Explanation: The input binary string 00000010100101000001111010011100 
    represents the unsigned integer 43261596,
     so return 964176192 which its binary representation is 00111001011110000010100101000000.
    Example 2:
    
    Input: 11111111111111111111111111111101
    Output: 10111111111111111111111111111111
    Explanation: The input binary string 11111111111111111111111111111101 
    represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 
    10111111111111111111111111111111.
     
    
    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 signed integer type and 
     should not affect your implementation, as the internal binary representation of 
     the integer 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 -3 and the output represents the signed integer -1073741825.
    

    分析过程

    • 题目归类:
      2进制
    • 题目分析:
      对于2进制需要了解补码反码左移右移逻辑右移和算术右移等操作。
      todo 各种码分析
    • 边界分析:
      • 空值分析
      • 循环边界分析
        需要了解到java中int是32位的所以转化成2进制应该是32位。
    • 方法分析:
      原数&1可以得到最后一位。然后把最后一位写到ref中。在对ref左移,对原数右移。
      • 数据结构分析
        int 32 位
      • 状态机
      • 状态转移方程
      • 最优解
    • 测试用例构建

    代码实现

    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            int ref=0;
            for(int i = 0; i < 32; i++) {
                int end = n&1;
                n>>=1;
                ref <<=1;
                ref |=end;
            }
            return ref;
        }
    }
    
    

    效率提高

    拓展问题

    Number of 1 Bits

  • 相关阅读:
    深度学习 框架比较
    深度学习 Fine-tune 技巧总结
    基于Spark环境对比Python和Scala语言利弊
    【Python系列】HDF5文件介绍
    【Git】CentOS7 通过源码安装Git
    【Git】Git工具常用命令
    登录自动跳转
    offset,scroll,client系列
    谷歌浏览器input中的text 和 button 水平对齐的问题
    git 的基本使用
  • 原文地址:https://www.cnblogs.com/clnsx/p/12298647.html
Copyright © 2011-2022 走看看