{"id":25737,"date":"2017-10-25T20:21:11","date_gmt":"2017-10-25T14:51:11","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25737"},"modified":"2017-10-25T20:21:11","modified_gmt":"2017-10-25T14:51:11","slug":"count-total-set-bits-numbers-1-n","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/count-total-set-bits-numbers-1-n\/","title":{"rendered":"Count total set bits in all numbers from 1 to n"},"content":{"rendered":"<p>Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n.<\/p>\n<p><strong>Examples:<\/strong><\/p>\n<pre>Input: n = 3\r\nOutput:  4\r\n\r\nInput: n = 6\r\nOutput: 9\r\n\r\nInput: n = 7\r\nOutput: 12\r\n\r\nInput: n = 8\r\nOutput: 13<\/pre>\n<p>We strongly recommend that you click here and practice it, before moving on to the solution.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 1 (Simple)<\/strong><br \/>\nA simple solution is to run a loop from 1 to n and sum the count of set bits in all numbers from 1 to n.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ A simple program to count set bits in all numbers from 1 to n.<br\/>#include &lt;stdio.h&gt;<br\/> <br\/>\/\/ A utility function to count set bits in a number x<br\/>unsigned int countSetBitsUtil(unsigned int x);<br\/> <br\/>\/\/ Returns count of set bits present in all numbers from 1 to n<br\/>unsigned int countSetBits(unsigned int n)<br\/>{<br\/>    int bitCount = 0; \/\/ initialize the result<br\/> <br\/>    for(int i = 1; i &lt;= n; i++)<br\/>       bitCount += countSetBitsUtil(i);<br\/> <br\/>    return bitCount;<br\/>}<br\/> <br\/>\/\/ A utility function to count set bits in a number x<br\/>unsigned int countSetBitsUtil(unsigned int x)<br\/>{<br\/>    if (x &lt;= 0)<br\/>        return 0;<br\/>    return (x %2 == 0? 0: 1) + countSetBitsUtil (x\/2);<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>   int n = 4;<br\/>   printf (&quot;Total set bit count is %d&quot;, countSetBits(n));<br\/>   return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Total set bit count is 5<\/pre>\n<p><strong>Time Complexity:<\/strong> O(nLogn)<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 2 (Tricky)<\/strong><br \/>\nIf the input number is of the form 2^b -1 e.g., 1,3,7,15.. etc, the number of set bits is b * 2^(b-1). This is because for all the numbers 0 to (2^b)-1, if you complement and flip the list you end up with the same list (half the bits are on, half off).<\/p>\n<p>If the number does not have all set bits, then some position m is the position of leftmost set bit. The number of set bits in that position is n \u2013 (1 &lt;&lt; m) + 1. The remaining set bits are in two parts: 1) The bits in the (m-1) positions down to the point where the leftmost bit becomes 0, and 2) The 2^(m-1) numbers below that point, which is the closed form above. An easy way to look at it is to consider the number 6:<\/p>\n<p>0|0 0<br \/>\n0|0 1<br \/>\n0|1 0<br \/>\n0|1 1<br \/>\n-|\u2013<br \/>\n1|0 0<br \/>\n1|0 1<br \/>\n1|1 0<br \/>\nThe leftmost set bit is in position 2 (positions are considered starting from 0). If we mask that off what remains is 2 (the \u201c1 0\u201d in the right part of the last row.) So the number of bits in the 2nd position (the lower left box) is 3 (that is, 2 + 1). The set bits from 0-3 (the upper right box above) is 2*2^(2-1) = 4. The box in the lower right is the remaining bits we haven\u2019t yet counted, and is the number of set bits for all the numbers up to 2 (the value of the last entry in the lower right box) which can be figured recursively.<\/p>\n<div class=\"line number1 index0 alt2\"><code class=\"c comments\"><\/code><\/div>\n<div class=\"line number1 index0 alt2\">\n<div class=\"line number1 index0 alt2\"><code class=\"c comments\">\/\/ A O(Logn) complexity program to count set bits in all numbers from 1 to n<\/code><\/div>\n<div class=\"line number2 index1 alt1\"><code class=\"c preprocessor\">#include &lt;stdio.h&gt;<\/code><\/div>\n<div class=\"line number3 index2 alt2\"><\/div>\n<div class=\"line number4 index3 alt1\"><code class=\"c comments\">\/* Returns position of leftmost set bit. The rightmost<\/code><\/div>\n<div class=\"line number5 index4 alt2\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c comments\">position is considered as 0 *\/<\/code><\/div>\n<div class=\"line number6 index5 alt1\"><code class=\"c plain\">unsigned <\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">getLeftmostBit (<\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">n)<\/code><\/div>\n<div class=\"line number7 index6 alt2\"><code class=\"c plain\">{<\/code><\/div>\n<div class=\"line number8 index7 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">m = 0;<\/code><\/div>\n<div class=\"line number9 index8 alt2\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c keyword bold\">while<\/code> <code class=\"c plain\">(n\u00a0 &gt; 1)<\/code><\/div>\n<div class=\"line number10 index9 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c plain\">{<\/code><\/div>\n<div class=\"line number11 index10 alt2\"><code class=\"c spaces\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<\/code><code class=\"c plain\">n = n &gt;&gt; 1;<\/code><\/div>\n<div class=\"line number12 index11 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<\/code><code class=\"c plain\">m++;<\/code><\/div>\n<div class=\"line number13 index12 alt2\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c plain\">}<\/code><\/div>\n<div class=\"line number14 index13 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c keyword bold\">return<\/code> <code class=\"c plain\">m;<\/code><\/div>\n<div class=\"line number15 index14 alt2\"><code class=\"c plain\">}<\/code><\/div>\n<div class=\"line number16 index15 alt1\"><\/div>\n<div class=\"line number17 index16 alt2\"><code class=\"c comments\">\/* Given the position of previous leftmost set bit in n (or an upper<\/code><\/div>\n<div class=\"line number18 index17 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c comments\">bound on leftmost position) returns the new position of leftmost<\/code><\/div>\n<div class=\"line number19 index18 alt2\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c comments\">set bit in n\u00a0 *\/<\/code><\/div>\n<div class=\"line number20 index19 alt1\"><code class=\"c plain\">unsigned <\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">getNextLeftmostBit (<\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">n, <\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">m)<\/code><\/div>\n<div class=\"line number21 index20 alt2\"><code class=\"c plain\">{<\/code><\/div>\n<div class=\"line number22 index21 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c plain\">unsigned <\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">temp = 1 &lt;&lt; m;<\/code><\/div>\n<div class=\"line number23 index22 alt2\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c keyword bold\">while<\/code> <code class=\"c plain\">(n\u00a0 &lt; temp)<\/code><\/div>\n<div class=\"line number24 index23 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c plain\">{<\/code><\/div>\n<div class=\"line number25 index24 alt2\"><code class=\"c spaces\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<\/code><code class=\"c plain\">temp = temp &gt;&gt; 1;<\/code><\/div>\n<div class=\"line number26 index25 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<\/code><code class=\"c plain\">m--;<\/code><\/div>\n<div class=\"line number27 index26 alt2\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c plain\">}<\/code><\/div>\n<div class=\"line number28 index27 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c keyword bold\">return<\/code> <code class=\"c plain\">m;<\/code><\/div>\n<div class=\"line number29 index28 alt2\"><code class=\"c plain\">}<\/code><\/div>\n<div class=\"line number30 index29 alt1\"><\/div>\n<div class=\"line number31 index30 alt2\"><code class=\"c comments\">\/\/ The main recursive function used by countSetBits()<\/code><\/div>\n<div class=\"line number32 index31 alt1\"><code class=\"c plain\">unsigned <\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">_countSetBits(unsigned <\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">n, <\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">m);<\/code><\/div>\n<div class=\"line number32 index31 alt1\">\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ Returns count of set bits present in all numbers from 1 to n<br\/>unsigned int countSetBits(unsigned int n)<br\/>{<br\/>   \/\/ Get the position of leftmost set bit in n. This will be<br\/>   \/\/ used as an upper bound for next set bit function<br\/>   int m = getLeftmostBit (n);<br\/> <br\/>   \/\/ Use the position<br\/>   return _countSetBits (n, m);<br\/>}<br\/> <br\/>unsigned int _countSetBits(unsigned int n, int m)<br\/>{<br\/>    \/\/ Base Case: if n is 0, then set bit count is 0<br\/>    if (n == 0)<br\/>       return 0;<br\/> <br\/>    \/* get position of next leftmost set bit *\/<br\/>    m = getNextLeftmostBit(n, m);<br\/> <br\/>    \/\/ If n is of the form 2^x-1, i.e., if n is like 1, 3, 7, 15, 31,.. etc, <br\/>    \/\/ then we are done. <br\/>    \/\/ Since positions are considered starting from 0, 1 is added to m<br\/>    if (n == ((unsigned int)1&lt;&lt;(m+1))-1)<br\/>        return (unsigned int)(m+1)*(1&lt;&lt;m);<br\/> <br\/>    \/\/ update n for next recursive call<br\/>    n = n - (1&lt;&lt;m);<br\/>    return (n+1) + countSetBits(n) + m*(1&lt;&lt;(m-1));<br\/>}<\/code><\/pre> <\/div>\n<div class=\"line number65 index64 alt2\"><code class=\"c comments\">\/\/ Driver program to test above functions<\/code><\/div>\n<div class=\"line number66 index65 alt1\"><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">main()<\/code><\/div>\n<div class=\"line number67 index66 alt2\"><code class=\"c plain\">{<\/code><\/div>\n<div class=\"line number68 index67 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c color1 bold\">int<\/code> <code class=\"c plain\">n = 17;<\/code><\/div>\n<div class=\"line number69 index68 alt2\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c functions bold\">printf<\/code> <code class=\"c plain\">(<\/code><code class=\"c string\">\"Total set bit count is %d\"<\/code><code class=\"c plain\">, countSetBits(n));<\/code><\/div>\n<div class=\"line number70 index69 alt1\"><code class=\"c spaces\">\u00a0\u00a0\u00a0<\/code><code class=\"c keyword bold\">return<\/code> <code class=\"c plain\">0;<\/code><\/div>\n<div class=\"line number71 index70 alt2\"><code class=\"c plain\">}<\/code><\/div>\n<pre>Total set bit count is 35\r\n\r\n<\/pre>\n<\/div>\n<\/div>\n<div class=\"line number1 index0 alt2\"><code class=\"c plain\"><\/code><\/div>\n<p><strong>Time Complexity:<\/strong> O(Logn). From the first look at the implementation, time complexity looks more. But if we take a closer look, statements inside while loop of getNextLeftmostBit() are executed for all 0 bits in n. And the number of times recursion is executed is less than or equal to set bits in n. In other words, if the control goes inside while loop of getNextLeftmostBit(), then it skips those many bits in recursion.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Count total set bits in all numbers from 1 to n &#8211; Bit Algorithm &#8211; In other words, if the control goes inside while loop of getNextLeftmostBit().<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,74852,83565],"tags":[75107,75101,75081,75119,70231,74371,75113,75108,75082,75094,75105,75115,75102,75087,75095,75114,75099,75103,75097,75110,75085,75083,75079,75088,75112,75111,75109,75078,75080,75091,75084,75093,75117,75098,75090,75106,73333,75089,75116,75096,75104,75120,75092,75100,75118,75086],"class_list":["post-25737","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-bit-algorithms","category-count-numbers","tag-32-bit-word","tag-8-bit-counter","tag-abit","tag-binary-bits","tag-binary-digit","tag-binary-numbers-table","tag-binary-words","tag-bit-binary-digit","tag-bit-bit-bit","tag-bit-counter-online","tag-bit-in-computer","tag-bit-manipulation","tag-bit-number","tag-bit-of-computer","tag-bit-packing","tag-bit-reversal","tag-bit-table","tag-bit-unit","tag-bitcomputer","tag-bitcount","tag-bitset","tag-bitwise-operations-in-c","tag-bitwise-operator-in-c","tag-bitwise-operator-in-c-example-programs","tag-c-bit","tag-c-byte","tag-c-xor","tag-clearbit","tag-computer-bit","tag-counter-bit-set","tag-counting-bits","tag-cs-counter","tag-define-count","tag-for-bit","tag-how-many-bits-in-a-byte","tag-java-binary-operators","tag-n-number-lookup","tag-nextbit","tag-one-bit","tag-python-integer-to-binary","tag-set-bit","tag-signed-binary-to-decimal","tag-total-set","tag-word-bit","tag-xor-operation-in-c","tag-xor-operator-in-c"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25737","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25737"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25737\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25737"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25737"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25737"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}