Easy
You are given two numbers a and b where 0 ≤ a ≤ b. Imagine you construct an array of all the integers from a to b inclusive. You need to count the number of 1s in the binary representations of all the numbers in the array.
Example
For a = 2 and b = 7, the output should be
rangeBitCount(a, b) = 11.
Given a = 2 and b = 7 the array is: [2, 3, 4, 5, 6, 7]. Converting the numbers to binary, we get [10, 11, 100, 101, 110, 111], which contains 1 + 2 + 1 + 2 + 2 + 3 = 11 1s.
Input/Output
-
[execution time limit] 0.5 seconds (c)
-
[input] integer a
Guaranteed constraints:
0 ≤ a ≤ b. -
[input] integer b
Guaranteed constraints:
a ≤ b ≤ 10. -
[output] integer
[C] Syntax Tips
// Prints help message to the console
// Returns a string
char * helloWorld(char * name) {
char * answer = malloc(strlen(name) + 8);
printf("This prints to the console when you Run Tests");
strcpy(answer, "Hello, ");
strcat(answer, name);
return answer;
}
더보기
Solution
int rangeBitCount(int a,int b)
{
int count=0;
for(int i=a;i<=b;i++)
for(int j=0;j<5;j++)
count+=(i&(1<<j))!=0;
return count;
}
728x90
'Codesignal' 카테고리의 다른 글
<Codesignal> Second-Rightmost Zero Bit (0) | 2020.04.12 |
---|---|
<Codesignal> Mirror Bits (0) | 2020.04.09 |
<Codesignal> Array Packing (0) | 2020.04.07 |
<Codesignal> Kill K-th Bit (0) | 2020.04.07 |
<Codesignal> Metro Card (0) | 2020.04.07 |