Count Set Bits in First N natural numbers | Total Set Bits from 1 to N | Bit Manipulation

Sdílet
Vložit
  • čas přidán 7. 09. 2020
  • Please consume this content on nados.pepcoding.com for a richer experience. It is necessary to solve the questions while watching videos, nados.pepcoding.com enables that.
    NADOS also enables doubt support, career opportunities and contests besides free of charge content for learning. In this video, we discuss the problem where we are required to find the set bits in the first N natural numbers using Bit Manipulation. In this problem,
    1. You are given a number n.
    2. You have to print the count of set bits of first n natural numbers.
    To submit this question, click here: www.pepcoding.com/resources/d...
    For a better experience and more exercises, VISIT: www.pepcoding.com/resources/o...
    #bitmanipulation #bitmasking
    Have a look at our result: www.pepcoding.com/placements
    Follow us on our FB page: / pepcoding
    Follow us on Instagram: / pepcoding
    Follow us on LinkedIn: / pepcoding-education

Komentáře • 195

  • @shivamagrawal2284
    @shivamagrawal2284 Před 3 lety +99

    Best explanation found after googling for more than 1hrs. Thank you

    • @Pepcoding
      @Pepcoding  Před 3 lety +7

      Glad it was helpful and If you like our efforts, please upvote the comments written by the students about Pepcoding here (www.quora.com/What-are-the-good-websites-to-learn-data-structures-and-algorithms )

    • @sumitsharma6738
      @sumitsharma6738 Před 2 lety +2

      sahi me bro

  • @vardhanshah8843
    @vardhanshah8843 Před 2 lety +25

    The approach of subtraction to convert it into recursion was amazing.

  • @pramodtarpe
    @pramodtarpe Před 3 lety +40

    You can use floor(log base 2(n)) to find 2 power x less than or equal to n.

    • @rishabsharma5307
      @rishabsharma5307 Před 2 lety +2

      Can you tell me why this is working?

    • @pramodtarpe
      @pramodtarpe Před 2 lety

      @@rishabsharma5307 thats the purpose of log

    • @ayushpatel2171
      @ayushpatel2171 Před 2 lety +21

      @@rishabsharma5307 In simple words logarithm is "How many of one number do we multiply to get another number?"
      Eg. log2(8) means how many 2s we need to multiply in order to get 8. The answer is 3, so the (log base 2(8)) = 3.
      Now if we do log base 2 for a number which is not a power of 2 we will get a decimal value eg. log base 2(10) = 3.322. And if we use floor function with log base 2(10) we will get 3. And 2^3 is highest power of 2 less than 10.

    • @rishabsharma5307
      @rishabsharma5307 Před 2 lety +4

      @@ayushpatel2171 thnx

  • @uttkarshsingh3771
    @uttkarshsingh3771 Před 2 lety +3

    Finally got some worthy content to look for. Pepcoding is great 🔥🔥🔥

  • @amreshgiri
    @amreshgiri Před 2 lety +11

    If implementing in Python, don't use the bit shifting method for calculating power as it will give negative shift value error when the value of x

    • @kusalsaraf5464
      @kusalsaraf5464 Před 2 lety

      Thanks a lot, but can you tell the reason as it working for even number but not for odds

  • @ManishKumar-zk5ky
    @ManishKumar-zk5ky Před rokem +1

    Best explanation on entire youtube sir
    Thanks a lot sir🤩

  • @Devendrakr63
    @Devendrakr63 Před 2 lety

    Best place to learn hard topics in easy way. Great!!!!

  • @kashbhalla4363
    @kashbhalla4363 Před rokem

    about to complete this series you are too good sir.

  • @lalitkumarmehta1721
    @lalitkumarmehta1721 Před 2 lety

    The way u explain is pretty awesome, Thanks, bro.

  • @b_1729-j8j
    @b_1729-j8j Před rokem

    Ur explanation is better than GFG article. Thank you.

  • @stith_pragya
    @stith_pragya Před rokem +1

    Thank You So Much Sumeet Sir.................🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @yashgupta9662
    @yashgupta9662 Před 2 lety

    A BIG Thanks for the explanation. 🙌

  • @binitrajshah9354
    @binitrajshah9354 Před 3 lety

    You explain great,
    kudos to you

  • @shashankbarole
    @shashankbarole Před 2 lety

    Thank you sir. This was the best explanation!

  • @rishijain8472
    @rishijain8472 Před rokem

    great explanation, best coding teacher on youtube
    2nd is striver

  • @sudhanshuuniyal5737
    @sudhanshuuniyal5737 Před rokem

    great explanation i was struggling from past two days.

  • @arijitchowdhury4189
    @arijitchowdhury4189 Před 4 dny

    Mszza ahh gaya sir ... Very good explanation. Thank you 🔥🔥🔥

  • @vikas5840
    @vikas5840 Před rokem

    thank you sir for such clear explanation

  • @RajSingh-YrBTechChemicalEnggII

    best explanation, better than google

  • @AbhishekSingh-fc2rx
    @AbhishekSingh-fc2rx Před 3 lety

    next level sir, its is very good explanation

  • @harshitbajaj7549
    @harshitbajaj7549 Před 2 lety

    Thank you so much sir, best explanation

  • @057anmolkesarwani4
    @057anmolkesarwani4 Před 2 lety

    Best Soln explanation for this question

  • @Prashantkumar-pn6qq
    @Prashantkumar-pn6qq Před 3 lety

    Thanks Sir! Nice work.

  • @UCVision93
    @UCVision93 Před rokem

    Clear cut explaination! Sir ji !

  • @csgirl6895
    @csgirl6895 Před 3 lety +2

    Thank you so much, Sir. Your way of explaining the solution is awesome. After watching your videos most difficult questions also become easy for me.

  • @powerofbasics869
    @powerofbasics869 Před 3 lety +1

    Sir I've jst started the getting started wala portion....
    And it is really really good..
    Bohat deep explanation Kiya Gaya h ..
    Thank u so much sir...
    Hope this channel will become the highest subscribed channel for coding.....:)

    • @Pepcoding
      @Pepcoding  Před 3 lety

      aapko agar sahi lag rha hai to ek review daal dijie
      g.page/Pepcoding/review?rc

  • @dontgiveup5271
    @dontgiveup5271 Před 2 lety +1

    Great explanation sir !! 👏👏 But I wanna know what are the complexities

  • @prayagpatel9136
    @prayagpatel9136 Před 2 lety

    Great explanation!!!!!

  • @vakhariyajay315
    @vakhariyajay315 Před rokem +1

    Nice Explanation

  • @ayushmishra9100
    @ayushmishra9100 Před 3 lety

    sir u are incredible!!!!

  • @yagizegemen7303
    @yagizegemen7303 Před 3 lety +4

    Sir the explanation is amazing. Appreciate your effort . Just a suggestion if you can also explain the Time and Space Complexity as well that would be great.

  • @neerajbhatia2008
    @neerajbhatia2008 Před 2 lety +1

    subscribing ur channel now. seriously man, you are too good. love your style of presentation and explanation, keep up the good work.

    • @Pepcoding
      @Pepcoding  Před 2 lety

      Thanks a ton!

    • @Pepcoding
      @Pepcoding  Před 2 lety +1

      For better experience, do checkout nados.pepcoding.com

  • @PulkitMalhotra
    @PulkitMalhotra Před 3 lety +7

    Thank you sir 1 number smz aa gya

    • @Pepcoding
      @Pepcoding  Před 3 lety +1

      Thankyou beta!
      Keep learning and keep loving Pepcoding😊
      If you like our efforts, will you like to write a few words about us here (www.quora.com/How-do-I-start-learning-or-strengthen-my-knowledge-of-data-structures-and-algorithms )

  • @rohitshinde8478
    @rohitshinde8478 Před 3 lety

    thank you for this amazing explaination

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Thankyou rohit for being aur constant supporter.
      Keep learning and keep loving Pepcoding😊

  • @samardhiman4365
    @samardhiman4365 Před 3 lety

    great explanation sir..

  • @manavpatnaik1948
    @manavpatnaik1948 Před 2 lety

    Very clear explanation. Thanks!

    • @Pepcoding
      @Pepcoding  Před 2 lety +1

      Glad it was helpful!
      Keep learning.
      And for better experience and well organised content visit nados.pepcoding.com

  • @karunakeshari1058
    @karunakeshari1058 Před 2 lety

    Best explanation💯

  • @mehirrouth7346
    @mehirrouth7346 Před 2 lety

    Amazing Explaination

  • @dhruvpurwar6642
    @dhruvpurwar6642 Před 2 lety

    Seriously tooo good!!!!

  • @jolly_dollyyy
    @jolly_dollyyy Před 3 lety

    excellent explanation sir

  • @samartajshaikh2601
    @samartajshaikh2601 Před 3 lety

    great explanation.

  • @lalitsoni9246
    @lalitsoni9246 Před 2 lety

    Great explanation...

  • @abhimanyu8575
    @abhimanyu8575 Před 3 lety

    does this program uses time complexity of theta logn??

  • @pradeepmondal4943
    @pradeepmondal4943 Před 3 lety

    Ekdaam faadu explaination ❤️❤️❤️❤️❤️❤️❤️ ..boleto jakhaas

    • @Pepcoding
      @Pepcoding  Před 3 lety

      If you like my efforts, I request a review
      g.page/Pepcoding/review?rc
      You can subscribe to our channel here
      czcams.com/users/Pepcodingabout?view_as=subscriber
      For clearing your doubts, you can join our community on telegram
      t.me/pepcoding

  • @kumarsundaram6762
    @kumarsundaram6762 Před rokem

    Great explanation.

  • @adarshjayadevan4379
    @adarshjayadevan4379 Před 3 lety

    Superb explanation. Thank you.

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Glad to know that you liked the content and thank you for appreciating.
      The love and respect which I get from you people keep me highly motivated and the same I am able to forward It to you people through my videos.
      If you like our efforts, will you like to write a few words about us here (www.quora.com/How-do-I-start-learning-or-strengthen-my-knowledge-of-data-structures-and-algorithms )

  • @divyansh3266
    @divyansh3266 Před 2 lety

    Best explanation..

  • @rishabhrawat7943
    @rishabhrawat7943 Před 2 lety

    Sir what is the time complexity of this approach. O(logN) or O(logN*logN)?

  • @myyoutubeisthis
    @myyoutubeisthis Před měsícem

    Thank you very much sir

  • @karankesri3648
    @karankesri3648 Před 3 lety +2

    For finding the largest of power 2 you can use log2(n) which will give the result in O(1)

  • @sonalisharma9654
    @sonalisharma9654 Před 2 lety

    Very nice explanation sir :)

  • @kunalkheeva
    @kunalkheeva Před rokem

    Thank you!

  • @systemforge
    @systemforge Před 3 lety +1

    Even though I don't know hindi.. i was able to understand it.. u r legend sir.. ❤️

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Great, Keep learning, Keep growing and keep loving Pepcoding!😊

  • @K-IT-VishalPanchal
    @K-IT-VishalPanchal Před rokem

    best explanation sir

  • @akhilagrawal4559
    @akhilagrawal4559 Před 3 lety

    Really Loved it Sir!!!

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Thank you for appreciating.
      The love and respect which I get from you people keep me highly motivated and the same I am able to forward It to you people through my videos.
      So, keep motivating, keep learning and keep loving Pepcoding😊

  • @rahulbhatia3075
    @rahulbhatia3075 Před 3 lety

    Amazing explanation 🔥🔥

  • @kaushiksarmah999
    @kaushiksarmah999 Před 3 lety

    thanks alot bro

  • @utkarsh_108
    @utkarsh_108 Před 2 lety

    thanks a lot

  • @utkrsh06
    @utkrsh06 Před 4 měsíci

    You freaking genius!

  • @harshalgarg1676
    @harshalgarg1676 Před 3 měsíci +1

    int countSetBits(int n)
    {
    if(n==0)
    return 0;
    int x = log(n)/log(2);
    int power = pow(2,x);
    int ans = (power/2)*x + (n-power+1) + countSetBits(n-power);
    return ans;
    }

  • @ruchaharshe6489
    @ruchaharshe6489 Před 2 lety

    nicely explained...thanks!!

    • @Pepcoding
      @Pepcoding  Před 2 lety

      Glad it was helpful! and If you like our efforts, please upvote the comments written by the students about Pepcoding here (www.quora.com/What-are-the-good-websites-to-learn-data-structures-and-algorithms )

  • @SaumyaSharma007
    @SaumyaSharma007 Před 3 lety +3

    thanks a lot, sir......
    you are really a great mentor. Your efforts justify Pepcoding's vision. (yesterday I watched your full interview......)
    huge respect for u SIR...Long live Sumeet SIR.
    Sir just want to ask u where can I get your full coding questions sheet (level 1,2).
    plzzzzz reply

    • @Pepcoding
      @Pepcoding  Před 3 lety +1

      I am glad. Keep learning. Keep supporting. Your kind words are the kind of motivation that truly help me in making more and more content. Especially, these days, not everybody is generous with motivating anybody either. It means a lot😊
      You can find this content on our website under free resources section, as there the content is given in a very structured and sequencial order. and out of which level-1 is almost complete and level-2 is still underprocess.

    • @SaumyaSharma007
      @SaumyaSharma007 Před 3 lety +1

      @@Pepcoding Thank you Sir 🌟🙏 for the reply......
      I am Big fan of yours 🙏

  • @shivammehta9661
    @shivammehta9661 Před 3 lety

    Nice Explanation..Keep making videos

  • @hiteshyadav2298
    @hiteshyadav2298 Před 3 lety

    I love the way you explained everything. Please use variable name in simplest form if possible. so that we can easily track flow of code. pls ignore words like - btill2x, msb2xton,etc

    • @Pepcoding
      @Pepcoding  Před 3 lety +2

      Thankyou beta,
      I am glad you liked it. I also hope that you are watching till end.
      If you like our efforts, will you like to write a few words about us here (www.quora.com/How-do-I-start-learning-or-strengthen-my-knowledge-of-data-structures-and-algorithms )

    • @hiteshyadav2298
      @hiteshyadav2298 Před 3 lety

      @@Pepcoding ✔

  • @kritikakashyap384
    @kritikakashyap384 Před 3 lety

    Nice way of teaching

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Thankyou beta!
      I am glad you liked it. I hope that you are watching till the end and trying to understand what, how, and especially why of the problem.
      If you like our efforts, will you like to write a few words about us here (www.quora.com/How-do-I-start-learning-or-strengthen-my-knowledge-of-data-structures-and-algorithms )

  • @subhadeeppal3127
    @subhadeeppal3127 Před 3 lety

    Perfect

  • @satyakidas9593
    @satyakidas9593 Před 3 lety

    what is the time complexity of this?

  • @AmanSharma-vb5jl
    @AmanSharma-vb5jl Před 2 lety

    What is the time complexity of this solution?

  • @vishalm784
    @vishalm784 Před 3 lety +2

    For getting largest power, we can use Math.floor(log2(num)) where log2 can be computed as Math.log(num)/Math.log(2);

    • @mickyman753
      @mickyman753 Před 3 lety +4

      but bitwise operations are faster

  • @sagarsattigeri9005
    @sagarsattigeri9005 Před rokem

    Will recurssion called only one? for all the cases

  • @raorao7329
    @raorao7329 Před dnem

    loveed the soln

  • @adityamhetras4799
    @adityamhetras4799 Před 2 lety

    Thanks you Sir!

    • @Pepcoding
      @Pepcoding  Před 2 lety

      Keep learning.
      And for better experience, visit nados.io, where you will get well curated content and career opportunities.

  • @itsyashh1308
    @itsyashh1308 Před 3 lety +3

    Sir I have a request and feedback, will you please show stats list on website that is really motivation to solve maximum number of questions in a day and questions serial number if possible ???

    • @Pepcoding
      @Pepcoding  Před 3 lety +1

      questions are in perfect order on portal. use portal instead of youtube. Yes, stats will be brought back.

  • @thejasnaveen4223
    @thejasnaveen4223 Před 2 lety

    Beautiful explanation ❤

    • @Pepcoding
      @Pepcoding  Před 2 lety

      Glad you liked it, for better experience and well organised content sign up on nados.io and start learning.

  • @vishalrajak2417
    @vishalrajak2417 Před 3 lety

    maje aa gaya bero solution dekkh ke

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Shukriya ji😊
      Bs aise he apna pyaar aur sahyog bnaye rkhe hum pr🙏

  • @nomaanahmad3357
    @nomaanahmad3357 Před 2 lety +2

    You could have used floor(log2(n)) to find largest power of 2 less than or equal to n. Though log2() function is not available in java but there are multiple ways to do so.

  • @surabhichoubey2987
    @surabhichoubey2987 Před rokem

    Nice sir

  • @ROHITKADYANJI
    @ROHITKADYANJI Před 3 lety

    Sumit sir 🤟🤟🤟
    Sir explanation is too good 🙌💯

    • @Pepcoding
      @Pepcoding  Před 3 lety

      keep motivating, keep learning and keep loving Pepcoding😊

  • @prakhyat2001
    @prakhyat2001 Před 2 lety

    thanks a lot :)))

  • @Radaradababurao
    @Radaradababurao Před 3 lety

    amazing content

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Thankyou beta!
      I am glad you liked it. I also hope that you are watching till the end and trying to understand the what, how, and especially why of the problem. If you like our efforts, will you like to review us here - g.page/Pepcoding/review?rc

  • @manideep7148
    @manideep7148 Před rokem

    Nice Explanation, It would be great if you had explained in english

  • @vamsimadugula8524
    @vamsimadugula8524 Před rokem

    It can be more easily solved using
    vector countBits(int n) {
    vector ans(n+1);
    for(int i=0;i

  • @labbusharma9865
    @labbusharma9865 Před 2 lety

    sir colour change kr liya kro please.... and best explanation

  • @akshayjadhav4199
    @akshayjadhav4199 Před rokem

    super 😍😍😍😍

  • @taukirlalwala2865
    @taukirlalwala2865 Před 3 lety

    thank u so much

  • @aravkhandelwal7043
    @aravkhandelwal7043 Před 2 lety +1

    very nice explanation

    • @Pepcoding
      @Pepcoding  Před 2 lety +1

      Thanks for liking. keep motivating, keep learning and keep loving Pepcoding😊

  • @prateeksomani5803
    @prateeksomani5803 Před 3 lety

    Sir, please also tell the time and space complexity of this approach

  • @omkark7118
    @omkark7118 Před rokem

    Can anyone please help me, how do I use the same logic using BigInteger class? Thank you in advance

  • @shahperzia1121
    @shahperzia1121 Před 3 lety

    In the Interview bit, this is partially correct. But why?

  • @Impromptu21
    @Impromptu21 Před 4 měsíci

    what's the time complexity?

  • @AryanKumar-cc7ku
    @AryanKumar-cc7ku Před 2 lety

    playlist of this video???

  • @amolshrivastava7786
    @amolshrivastava7786 Před 3 lety +1

    Thank you sir, sab smjh m aa gaya after this solution ...also m phele pow(2,x) use karta tha but from now on i'll use (1x) to get 1/2^x.

  • @AyushRaj-gf2ce
    @AyushRaj-gf2ce Před 3 lety

    sir solution toh samjh aaraha bit manipulatio series ka..but ek problem hai..intuition nahi aaraha..jaise dp ya backtracking me pata hota tha ki jo bhi ki ku kiya..but in sab me aisa lag raha bas solution samjh aaraha..intuition develop nahi ho raha..any advice for that? Bit manipulation ki practice kaha se kiya jaiye?

    • @Pepcoding
      @Pepcoding  Před 3 lety

      beta 5-6 tricks he hain, iske liye jo maths important hai wo set theory hai.
      My suggestion
      1. Understand basic operations of bits
      2. Revise set theory
      3. Do these 30 questions, now go and test yourself on a random set of questions you will perform better.

  • @payalsagar1808
    @payalsagar1808 Před 3 lety

    Wow!

    • @Pepcoding
      @Pepcoding  Před 3 lety

      I am glad you liked it. I also hope that you are watching till end and trying to understand the what, how and especially why of the problem.
      If you like our efforts, we request a review
      g.page/Pepcoding/review?rc
      You can subscribe to our channel here
      czcams.com/users/Pepcodingabout?view_as=subscriber

  • @abhijeetsingh9796
    @abhijeetsingh9796 Před 2 lety

    Time complexity of this code?

  • @aparajitakumari2936
    @aparajitakumari2936 Před 2 lety

    How is he using bitwise left shift operator to calculate power?
    Please explain.

    • @Pepcoding
      @Pepcoding  Před 2 lety

      For clearing all your doubts visit on nados.pepcoding.com
      Don't forget to follow us on Instagram instagram.com/pepcoding/

  • @mohdsarfarazkhan2799
    @mohdsarfarazkhan2799 Před 3 lety

    Respect bro

    • @Pepcoding
      @Pepcoding  Před 3 lety

      If you like our efforts, we request a review
      g.page/Pepcoding/review?rc
      You can subscribe to our channel here
      czcams.com/users/Pepcodingabout?view_as=subscriber
      For clearing your doubts, you can join our community on telegram
      t.me/pepcoding

  • @AdityaSingh-ux4bk
    @AdityaSingh-ux4bk Před 3 lety +2

    Thanks a lot, your video helped me a lot..
    I have optimized your code which runs even faster.. hope it helps others
    { int sum = 0;
    int x;
    while(n>0){
    x = floor(log(n)/log(2));
    sum += x * (1

    • @nomaanahmad3357
      @nomaanahmad3357 Před 2 lety +2

      thanks for the optimization! Appreciate your help

  • @saloniranka5609
    @saloniranka5609 Před 2 lety +1

    Going forward, can you please add time and space complexity in the end as well, it would be of more help to the existing content

    • @Devendrakr63
      @Devendrakr63 Před 2 lety +1

      Time complexity would be O(logn) , since we are dividing the problem into two parts in each call. And Stack Space take by the algo will also be O(logn), since there are log n recursive function calls.

    • @omprakashbarupal2129
      @omprakashbarupal2129 Před rokem

      @@Devendrakr63 ig TC is O(longn)^2, as recursive call has TC logn and in each call we
      we finding 2's power less than n has also TC as logn.

    • @omprakashbarupal2129
      @omprakashbarupal2129 Před rokem +1

      TC is O(longn)^2, as recursive call has TC logn and in each call we
      we finding 2's power less than n has also TC as logn.

  • @mickyman753
    @mickyman753 Před 3 lety

    fabulous explaination , you made it so easy to understand , i saw the of the same problem on gfg and after hitting my head for several minutes and still not getting it ,saw your explanation ,love you sir

    • @Pepcoding
      @Pepcoding  Před 3 lety +1

      Thankyou beta!
      I am glad you liked it. I hope that you are watching till the end and trying to understand what, how, and especially why of the problem.
      If you like our efforts, will you like to write a few words about us here (www.quora.com/How-do-I-start-learning-or-strengthen-my-knowledge-of-data-structures-and-algorithms )

    • @mickyman753
      @mickyman753 Před 3 lety

      @@Pepcoding yes sir i will , and will wait for question solving videos ,they are so good