![]() |
VOOZH | about |
Given N, the row number of Pascal's triangle(row starting from 0). Find the count of odd numbers in the N-th row of Pascal's Triangle.
Prerequisite: Pascal's Triangle | Count number of 1's in binary representation of N
Examples:
Input : 11 Output : 8 Input : 20 Output : 4
Approach: It appears the answer is always a power of 2. In fact, the following theorem exists:
THEOREM: The number of odd entries in row N of Pascal's Triangle is 2 raised to the number of 1's in the binary expansion of N.
Example: Since 83 = 64 + 16 + 2 + 1 has binary expansion (1010011), then row 83 has pow(2, 4) = 16 odd numbers.
Below is the implementation of the above approach:
4
Time Complexity: O(L), where L is the length of a binary representation of a given N.
Space Complexity: O(1)