zoukankan      html  css  js  c++  java
  • 剑指offer

    八、位运算

    1. 二进制中1的个数

    题目描述:

    ​ 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

    思路:

    常规解法:

    ​ 首先把n和1做与运算,判断n的最低位是不是1。接着把n左移一位,再和n做与运算,判断次低位是不是1……这样反复左移,就能从右至左依次判断n的每一位是不是1。

    优解:

    ​ 若对于一个int类型的整数,它由32位2进制来表示,则上面的常规解法需要循环32次。下面再介绍一种算法,整数中有几个1就只需要循环几次。

    ​ 把一个整数减去1的结果与原整数做与运算,这样会把该整数最右边的1变成0。那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。

    代码:

    常规解法:

    public class Solution {
        public int NumberOf1(int n) {
            int count = 0;
            int flag = 1;
            while (flag != 0) {
                if ((n & flag) != 0) {
                    count++;
                }
                flag = flag << 1;
            }
            return count;
        }
    }
    

    优解:

    public class Solution {
        public int NumberOf1(int n) {
            int count = 0;
            while (n != 0) {
                count++;
                n = (n - 1) & n;
            }
            return count;
        }
    }
    
  • 相关阅读:
    Piggy-Bank (hdoj1114)
    Word Amalgamation(hdoj1113)
    Lowest Bit(hdoj1196)
    1206: B.求和
    1207: C.LU的困惑
    STL初步
    关于521(nyoj)
    first blood暴力搜索,剪枝是关键
    变态最大值(nyoj)
    烧饼(nyoj779)
  • 原文地址:https://www.cnblogs.com/jiajun107/p/12492599.html
Copyright © 2011-2022 走看看