首页 > 其他 > 详细

LeetCode - Reverse Bits

时间:2015-04-01 01:40:13      阅读:295      评论:0      收藏:0      [点我收藏+]

          二进制转换和字符串逆序。要考虑int的范围,测试数据是有溢出的。Math.pow是有精度损失的,最好写成整数的。

 

  

public class ReverseBits {
    
    public static int reverseBits(int n) {
        StringBuilder sb = new StringBuilder(Integer.toBinaryString(n));
        StringBuilder s = new StringBuilder(sb.reverse());
        if(s.length()!=32) {
            while(s.length() != 32) {
                s.append("0");
            }
        }
        //System.out.println(s);
        int ans = 0;
        for(int i=s.length()-1; i>=0; i--) {
            if(s.charAt(i) == ‘1‘) {
                //System.out.println(s.length()-1-i);
                ans += pow(2, s.length()-1-i);
            }
        }
        return ans;
    }
    public static int pow(int n, int m) {
        int ans = 1;
        for(int i=0; i<m; i++) {
            ans *= n;
        }
        ans = Math.abs(ans);
        return ans;
    }

 

LeetCode - Reverse Bits

原文:http://www.cnblogs.com/wxisme/p/4382499.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!