关闭

Leetcode-191. Number of 1 Bits

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

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question
写一个函数 返回一个无符号整形数中“1”的数量;
比如32位整数11的二进制数为00000000000000000000000000001011;函数输出3;

public class Solution {
        public static int hammingWeight(int n) {
        String s = Integer.toBinaryString(n).toString().trim();
        int m = 0;
        for(int i = 0 ; i < s.length(); i++){
            if("1".equals(s.substring(i, i+1))){
                m += 1;
            }
        }
        return m; 
        }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:15488次
    • 积分:584
    • 等级:
    • 排名:千里之外
    • 原创:15篇
    • 转载:4篇
    • 译文:33篇
    • 评论:3条
    最新评论