365. Count 1 in Binary【LintCode java】
阿新 • • 發佈:2018-07-14
body param repr rip mark ive app int solution
Description
Count how many 1
in binary representation of a 32-bit integer.
Example
Given 32
, return 1
Given 5
, return 2
Given 1023
, return 9
Challenge
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】