C++ | Diagram | Related Problems
\n\n\n\n\ncpp\nclass Solution {\npublic:\n    \n    int numberOfBits(int n) {\n\t\t  return log2(n) + 1;\n    }\n    \n    int concatenatedBinary(int n) {\n    
![image](https://assets.leetcode.com/users/images/6822f124-b599-40a1-96d6-5e6111ee2ca9_1663902113.3584025.png)\n\n![image](https://assets.leetcode.com/users/images/c3eecab6-bc21-49e9-b535-fc455f96fe8e_1663903076.2444859.png)\n\n\n```cpp\nclass Solution {\npublic:\n    \n    int numberOfBits(int n) {\n\t\t  return log2(n) + 1;\n    }\n    \n    int concatenatedBinary(int n) {\n        long ans = 0, MOD = 1e9 + 7;\n        \n        for (int i = 1; i <= n; ++i) {\n            int len = numberOfBits(i);\n            ans = ((ans << len) % MOD + i) % MOD;\n        }\n        return ans;\n    }\n};\n```\n\n**EDIT 1**\n**Optimization** in `numberOfBits` function\n```cpp\nint numberOfBits(int n) {\n   int leadingZeros = __builtin_clz(n);\n   return 32 - leadingZeros;\n}\n```\n\n**EDIT 2**\nAnother way of **calculating length of binary number** suggested by @CoolBud\n```cpp\nint numberOfBits(int n) {\n    return log2(n) + 1;\n}\n```\n\n**EDIT 3**\nAnother way of **calculating length of binary number** suggested by @Sopindm\n```cpp\nint concatenatedBinary(int n) {\n        long ans = 0, MOD = 1e9 + 7, len = 0;\n        for (int i = 1; i <= n; ++i) {\n            if(__builtin_popcount(i) == 1) ++len;\n            ans = ((ans << len) % MOD + i) % MOD;\n        }\n        return ans;\n}\n```\n\n**Binary Representation Related Problems**\n[1. Add Binary ](https://leetcode.com/problems/add-binary/)\n[2. Add Two Numbers ](https://leetcode.com/problems/add-two-numbers/)\n[3. Counting Bits ](https://leetcode.com/problems/counting-bits/)\n[4. Binary Watch ](https://leetcode.com/problems/binary-watch/)\n[5. Reverse Bits ](https://leetcode.com/problems/reverse-bits/)\n[6. Binary Number with Alternating Bits ](https://leetcode.com/problems/binary-number-with-alternating-bits/)\n[7. Hamming Distance ](https://leetcode.com/problems/hamming-distance/)\n[8. Prime Number of Set Bits in Binary Representation ](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/)
['Bit Manipulation', 'C', 'C++']