zoukankan      html  css  js  c++  java
  • 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


    My code:
    1
    public class ReverseBits { 2 3 public static void main(String[] args) { 4 // TODO Auto-generated method stub 5 ReverseBits test = new ReverseBits(); 6 7 System.out.println(test.reverseBits(43261597)); 8 } 9 10 // Accepted 11 public long reverseBits(int n) { 12 13 String str = Integer.toBinaryString(n); 14 StringBuilder sb = new StringBuilder(); 15 int len = str.length(); 16 17 for(int i = len -1; i >=0 ; i--) 18 { 19 sb.append(str.charAt(i)); 20 } 21 for(int i = len; i < 32; i++) 22 { 23 sb.append("0"); 24 } 25 26 long base = 1; 27 long re = 0; 28 for(int i = 31 ; i >=0; i--) 29 { 30 if( sb.charAt(i) == '1') 31 { 32 re += base; 33 } 34 base *=2; 35 } 36 return re; 37 } 38 }
  • 相关阅读:
    js中this的用法
    js原型链与继承(初体验)
    关于C语言指针中的p++与p+i
    react todolist
    react表单提交
    react条件渲染
    react初体验
    初次接触express
    阿里内推在线编程题(返回元素的选择器)
    模块初始化
  • 原文地址:https://www.cnblogs.com/ordili/p/4928272.html
Copyright © 2011-2022 走看看