Detailed Thought Process with Steps Example | O(n) Time | Java 8 1-Liner
\nn = 3\n1 - 1\n2 - 10\n3 - 11\n\n123 -> 11011 --> \n\n(1 * 2^4) + (1 * 2 ^3 + 0 * 2 ^ 2) + (1 * 2^1 + 1 * 2^0)\n\n(1 * 2^4) + (2 * 2 ^2 + 0 * 2 ^ 2) + (2 * 2^0
```\nn = 3\n1 - 1\n2 - 10\n3 - 11\n\n123 -> 11011 --> \n\n(1 * 2^4) + (1 * 2 ^3 + 0 * 2 ^ 2) + (1 * 2^1 + 1 * 2^0)\n\n(1 * 2^4) + (2 * 2 ^2 + 0 * 2 ^ 2) + (2 * 2^0 + 1 * 2^0)\n\n(1 * 2^4) + (2 + 0) * 2 ^2  + (2 + 1)* 2^0\n\n(1)* 2^4 + (2) * 2 ^2  + (3)* 2^0\n\n((1)* 2^4 + (2) * 2 ^2)  + (3)* 2^0\n\n((1)* 2^2 + (2)) * 2 ^2)  + (3)* 2^0\n\n(4 + 2) * 2^2 + 3\n\n24 + 3 \n\n27\n\n```\n\n```\nclass Solution {\n    public int concatenatedBinary(int n) {\n        int MOD = 1_000_000_007;\n        long sum = 0;\n        for (int i = 1; i <= n; i++)\n            sum = (sum * (int)Math.pow(2, Integer.toBinaryString(i).length()) + i) % MOD; // sum = ((sum << Integer.toBinaryString(i).length()) + i) % MOD;\n\n        return (int)sum;\n    }\n}\n```\n\n****************\n\n**Bitwise O(n) Time**\n\n```\nclass Solution {\n    // TC - O(n)\n    public int concatenatedBinary(int n) {\n        int MOD = 1_000_000_007;\n        long sum = 0;\n        int length = 0;\n        \n        for(int i = 1; i <= n; i++) {\n            if((i & (i - 1)) == 0)\n                length++;\n            sum = ((sum << length) | i) % MOD;\n        }\n        \n        return (int) sum;\n    }\n}\n```\n\n****************\n\nJava-8: 1 Liner using Long.range and reduce\n\n```\nclass Solution {\n    public int concatenatedBinary(int n) {\n\t\treturn (int) LongStream.range(1, n + 1).reduce(0, (sum, i) -> (sum * (int) Math.pow(2, Long.toBinaryString(i).length()) + i) % 1_000_000_007);\n    }\n}\n```\n\n\nIf you like solution - **upvote**.
[]