Leetcode-191. Number of 1 Bits

来源:互联网 发布:php跳转页面 编辑:程序博客网 时间:2024/04/30 01:22

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
原创粉丝点击