一个正整数int有多少bit位为一

来源:互联网 发布:mysql数据库设计原则 编辑:程序博客网 时间:2024/06/11 05:25

https://leetcode.com/problems/number-of-1-bits/

题目

给一个正整数int,输出bit位为一的个数。

解法1

public static int bitCount(int x) {int count  = 0;while(x > 0) {count += (x % 2);x = x / 2;}return count;}
如果是9 计算4次
解法2

public static int bitCount(int x) {int count  = 0;while(x > 0) {// 可以去掉最右那个为1的bit位x = x & (x-1);count++;}return count;}
如果是9计算2次

0 0
原创粉丝点击