[Java] Simple
1680. Concatenation of Consecutive Binary Numbers\n\nclass Solution {\n    public int concatenatedBinary(int n) {\n        int i=1;\n        int mod = (int)Math
**1680. Concatenation of Consecutive Binary Numbers**\n```\nclass Solution {\n    public int concatenatedBinary(int n) {\n        int i=1;\n        int mod = (int)Math.pow(10,9) + 7;\n        StringBuilder sb = new StringBuilder();\n        while(i<=n){\n            sb.append(Integer.toBinaryString(i)); // Build string with integers\n            i++;\n        }\n        String binary = sb.toString();\n        int current = 0;\n        for(i=0; i<binary.length();i++){\n            current += binary.charAt(i) ==\'1\'? 1:0; // add 1 if it is a 1\n            if(i+1 != binary.length()) // only multiply if it is not the last place or else it will be too big!\n                current = ((current % mod) * 2) % mod; // modular multiplication to avoid overflow\n        }\n        return current;\n    }\n}\n```\n**PROBLEM OVERVIEW**\nGiven an int, n, concatenate all numbers from 1 to n in binary. Convert this binary number into decimal. Numbers may be large so return the answer mod 10^9 + 7.\n\n**SOLUTION ANALYSIS**\nUse a StringBuilder for efficient String concatenation. For each decimal value 1 to n, we can use Java\'s inbuilt function Integer.toBinaryString(int i) to concatenate the binary representation.\n\nAfter that, we need to use modular multiplication to avoid overflow. To convert binary to decimal, we typically add 1 if it is a 1 at that place value and then multiply the sum by 2. However, bcause the number may be too large, we take the remainder of the current number and mod (10^9 + 7) before and after multiplying. By doing so, we prevent overflow.\n\nFor modular multiplication, the typical code is like this :\n```\npublic int modularMultiplication(int a, int b, int mod){\n\treturn ((a%mod) * (b%mod)) % mod;\n}\n```\n\n
[]