1 class Solution {
2 public:
3 /**
4 * @param num: an integer
5 * @return: an integer, the number of ones in num
6 */
7 int countOnes(int num) {
8 // write your code here
9 int num_bit[32]={0};
10 int one_count = 0;
11 int i,num2 = num;
12 // 负数转正,符号位变1
13 if(num < 0) {
14 num = num * -1;
15 num_bit[31] = 1;
16 }
17 // 十进制转二进制
18 for(i=0; num; i++) {
19 num_bit[i] = num%2;
20 num /= 2;
21 }
22 // 负数原码转补码
23 if(num2 < 0) {
24 for(i=30; i>=0; i--) {
25 if(num_bit[i] == 1)
26 break;
27 num_bit[i] = 1;
28 }
29 }
30 for(i=0; i<32; i++) {
31 if(num_bit[i] == 1)
32 one_count++;
33 }
34 return one_count;
35 }
36 };