zoukankan      html  css  js  c++  java
  • LintCode-二进制中有多少个1

    题目:

    计算在一个 32 位的整数的二进制表示中有多少个 1.

    样例

    给定 32 (100000),返回 1

    给定 5 (101),返回 2

    给定 1023 (111111111),返回 10

    编程:

    方式一:普通方法(思路就是进行断除,注意先判断余数 L10 再覆盖原来的整数 L13 的顺序)

     1 public class Solution {
     2     /**
     3      * @param num: an integer
     4      * @return: an integer, the number of ones in num
     5      */
     6     public int countOnes(int num) {
     7         // write your code here
     8         int count = 0 ;
     9         while(num!=0){
    10             if(num%2==1){
    11                 count++;
    12             }
    13             num = num/2;
    14         }
    15         return count ;
    16     }
    17 };

     

    方式二:高效方法(位运算,且需要知道n&(n-1)的作用可以消掉最右边的1)

    其原理是不断清除n的二进制表示中最右边的1,同时累加计数器,直至n为0。
    为什么n &= (n – 1)能清除最右边的1呢?因为从二进制的角度讲,n相当于在n - 1的最低位加上1。
    举个例子,8(1000)= 7(0111)+ 1(0001),所以8 & 7 = (1000)&(0111)= 0(0000),清除了8最右边的1(其实就是最高位的1,因为8的二进制中只有一个1)。再比如7(0111)= 6(0110)+ 1(0001),所以7 & 6 = (0111)&(0110)= 6(0110),清除了7的二进制表示中最右边的1(也就是最低位的1)
     1 public class Solution {
     2     /**
     3      * @param num: an integer
     4      * @return: an integer, the number of ones in num
     5      */
     6     public int countOnes(int num) {
     7         // write your code here
     8         int count = 0 ;
     9         while(num!=0){
    10             num = num&(num-1);
    11             count++;
    12         }
    13         return count ;
    14     }
    15 };
  • 相关阅读:
    js-url打开方式
    eclipse删除所有空行
    Oracle重启 error: ora-01034:oracle not available ora-27101:shared memory realm does not exist
    最近面试遇到了高阶函数的概念混乱了
    关于跨域的cookie问题
    二叉树 呜呜
    函数的尾递归
    react context
    二叉树
    dom3级事件
  • 原文地址:https://www.cnblogs.com/crazytrip/p/7345748.html
Copyright © 2011-2022 走看看