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; } };
原文地址:https://www.cnblogs.com/phdeblog/p/9308849.html
时间: 2024-10-09 18:59:59