关闭

LeetCode Number of 1 Bits

标签: javaleetcodeDP
142人阅读 评论(0) 收藏 举报
分类:

Description:

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

Solution:


import java.util.*;

public class Solution {
	public int hammingWeight(int n) {
		int count = 0;
		String s = Integer.toBinaryString(n);
		for (int i = 0; i < s.length(); i++)
			if (s.charAt(i) == '1')
				count++;
		return count;
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:62754次
    • 积分:3262
    • 等级:
    • 排名:第10459名
    • 原创:288篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    最新评论