标签:one wrapper ++ The ret markdown des bin math
Count how many 1
in binary representation of a 32-bit integer.
Given 32
, return 1
Given 5
, return 2
Given 1023
, return 9
If the integer is n bits with m 1 bits. Can you do it in O(m) time?
解题:很简单,但是要考虑范围的问题。代码如下:
public class Solution {
/*
* @param num: An integer
* @return: An integer
*/
public int countOnes(int num) {
// write your code here
int count = 0;
long temp = (long)num;
if(temp < 0){
temp = (long)Math.pow(2,32) + temp;
}
while(temp != 0){
if(temp %2 == 1)
count++;
temp = temp / 2;
}
return count;
}
};
365. Count 1 in Binary【LintCode java】
标签:one wrapper ++ The ret markdown des bin math
原文地址:https://www.cnblogs.com/phdeblog/p/9308849.html