DEV Community

Cover image for Day 57 of 100 days dsa coding challenge
Manasi Patil
Manasi Patil

Posted on

Day 57 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! πŸ’»πŸ”₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! πŸš€

100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney

Problem:

https://www.geeksforgeeks.org/problems/count-total-set-bits-1587115620/1

Count set bits

Difficulty: Medium Accuracy: 35.77%

You are given a number n. Find the total count of set bits for all numbers from 1 to n (both inclusive).

Examples :

Input: n = 4
Output: 5
Explanation: For numbers from 1 to 4. for 1: 0 0 1 => 1 set bit, for 2: 0 1 0 => 1 set bit, for 3: 0 1 1 => 2 set bits, for 4: 1 0 0 => 1 set bit. Therefore, the total set bits are 5.
Input: n = 17
Output: 35
Explanation: From numbers 1 to 17(both inclusive), the total number of set bits are 35.
Constraints:
1 ≀ n ≀ 108

Solution:
class Solution:
def countSetBits(self, n):
if n == 0:
return 0
x = n.bit_length() - 1
p = 1 << x
return x * (p >> 1) + (n - p + 1) + self.countSetBits(n - p)

Top comments (0)