写在前面:
为了增长一下自己的数据结构能力,也为了面试准备,准备将剑指Offer做一下,并与各位分享,希望各位可以对代码以及思路提提建议,欢迎志同道合者,谢谢。
题目
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
思路:
这个有两种解决办法,
一种是java自带的api
一种是使用&计算,(网上看的,但是不大懂)
代码实现
public static int numberOfOne2(int n) { int count = 0; while (n != 0) { count++; n = n & (n - 1); } return count; } public static int numberOfOne1(int n) { int count = 0; String str = Integer.toBinaryString(n); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '1') { count++; } } return count; }
作者:z七夜
链接:https://www.jianshu.com/p/adbf0d370aac