easy
0 views

Function getOnesCount – CTS PATTERN

Fix the given function to correctly count the number of 1's in the binary representation of an integer.

Understand the Problem

Problem Statement

You are required to fix all logical errors in the given code. You can click on Run anytime to check the compilation/execution status of the program. You can use printf to debug your code. The submitted code should be logically/syntactically correct and pass all test cases. Do not write the main() function as it is not required.

Code Approach: For this question, you will need to correct the given implementation. We do not expect you to modify the approach or incorporate any additional library methods.

The function getOnesCount(int N) accepts an integer N as the input. The function is supposed to return the count of 1’s in the binary representation of N.

The function compiles fine but fails to return the desired result due to logical error.

Your task is to fix the program so that it passes all test cases.

Constraints

  • The input integer N can be any 32-bit signed integer (including negative numbers)
  • The function should handle both positive and negative integers correctly
  • The output should be a non-negative integer representing the count of 1's
  • Time complexity should be O(log N) for the number of bits in N
  • Space complexity should be O(1)

Examples

Example 1
Input
5
Output
2
Explanation

The binary representation of 5 is 101, which contains two 1's.

Example 2
Input
-1
Output
32
Explanation

The binary representation of -1 in 32-bit two's complement is all 1's (11111111111111111111111111111111), so it contains 32 ones.

Example 3
Input
0
Output
0
Explanation

The binary representation of 0 is 0, which contains zero 1's.

Solution

int getOnesCount(int N){
    unsigned int num = (unsigned int)N;
    int count = 0;
    while(num > 0){
        if(num & 1){
            count += 1;
        }
        num >>= 1;
    }
    return count;
}
Time:O(log N) where log N represents the number of bits in the number
Space:O(1) - constant space usage
Approach:

This C solution fixes the original code by:

  1. Converting the input to unsigned int to handle negative numbers correctly
  2. Using bitwise AND (num & 1) to check if the least significant bit is 1
  3. Using right shift (num >>= 1) to move to the next bit position
  4. Continuing until all bits are processed

The unsigned conversion ensures that negative numbers are treated as their full 32-bit representation, allowing us to count all the 1's including the sign extension bits.

Visual Explanation

Loading diagram...