Love丶FFC's Blog

LintCode_easy:判断一个整数中有多少个1

2019-08-30 12:27:20
阅读:504   •   评论:7
标签:,

描述

写一个函数,其以无符号整数为输入,而输出对应二进制数所具有的“1”的位数(也被称为汉明权重)

样例

样例 1

输入:n = 11
输出:3
解析:11(10) = 1011(2), 返回 3

样例 2

输入:n = 7
输出:3
解析:7(10) = 111(2), 返回 3

编程语言:Java

解题思想:

1.直接使用十进制数转二进制数的算法即可。

2.如11(10)转换为二进制数的过程为:

11/2=5,此时余数=1。

5/2=2,此时余数=1。

2/2=1,此时余数为0。

1/2=0,此时余数为1。

因此11(10)=1011(2),本题直接累加余数为1的次数即可。

时间复杂度:O(logN)

IDE代码如下:

  1. public class Solution {
  2. public int hammingWeight(int n) {
  3. int total=0;
  4. while(n!=0)
  5. {
  6. total=(n%2==1)?total+1:total;
  7. n/=2;
  8. }
  9. return total;
  10. }
  11. }

LintCode编辑器代码如下:

  1. public class Solution {
  2. public int hammingWeight(int n) {
  3. int total=0;
  4. while(n!=0)
  5. {
  6. total=(n%2==1)?total+1:total;
  7. n/=2;
  8. }
  9. return total;
  10. }
  11. }

评论板

共有 7 条评论

  1. Jorcift

    Finally, in vitro studies have shown that epigenetic reprogramming might play a central role in ERО± BC cells that adapt to endocrine therapy 16, 17 propecia viagra combined Recent studies report the prevalence of taste disturbances in chemotherapy patients is high, ranging from 65 to 80 1 5

  2. intuido

    levitra que hace Also see our top choices for L Theanine

  3. intuido

    Cells were transfected with Atg7 siRNA Santa Cruz, sc 41448 or Tlr4 siRNA Santa Cruz, sc 40261 using lipofectamine 2000 Invitrogen buy cialis 5mg

  4. iEUPyqgxw

    Prigge ST, Kolhekar AS, Eipper BA et al 1999 Substrate mediated electron transfer in peptidylglycine alpha hydroxylating monooxygenase generic propecia

--------查看该分类下最新文章--------
^
新版博客正在完善中!域名:http://www.loveffc:8080,点击跳转,完全移植后将去除端口号。

Copyright © 2018 - 2021 FFC的小站 - 滇 ICP 备 18010780 号 - 1

- Powered by WordPress & AliYun · Theme by FFC -

- Environment by Windows & XAMPP · Designed by WebStorm & VSCode -

已运行:

访问量:502891