Javascript | Easy Solution | beats 95%
(Note: This is part of a series of Leetcode solution explanations (index). If you like this solution or find it useful, please upvote this post.)\n\n---\n\nIdea
*(Note: This is part of a series of Leetcode solution explanations ([**index**](https://dev.to/seanpgallivan/leetcode-solutions-index-57fl)). If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n***Idea:***\n\nThere are less efficient solutions which involve converting numbers to strings, or calculating the binary length each time, but the most efficient solution is actually even more basic, since we know precisely when a binary number will increase its length by 1.\n\nSo we can just iterate through while using **len** to keep track of how much you need to multiply **ans** by in order to fit **i** into the new **ans**. Don\'t forget to mod by **1e9+7**.\n\n---\n\n***Javascript Code:***\n\nThe best result for the code below is **148ms / 39.8MB** (95% / 84%).\n```javascript\nvar concatenatedBinary = function(n) {\n    let ans = 1, len = 0b100\n    for (let i = 2; i <= n; i++) {\n        if (i === len) len <<= 1\n        ans = (ans * len + i) % 1000000007\n    }\n    return ans\n};\n```\nThe same code but with decimal instead of binary for **len**:\n```javascript\nvar concatenatedBinary = function(n) {\n    let ans = 1, len = 4\n    for (let i = 2; i <= n; i++) {\n        if (i === len) len *= 2\n        ans = (ans * len + i) % 1000000007\n    }\n    return ans\n};\n```
['JavaScript']