1680. Concatenation of Consecutive Binary Numbers

package LeetCode_1680

/**
 * 1680. Concatenation of Consecutive Binary Numbers
 *https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/
 * Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.

Example 1:
Input: n = 1
Output: 1
Explanation: "1" in binary corresponds to the decimal value 1.

Example 2:
Input: n = 3
Output: 27
Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
After concatenating them, we have "11011", which corresponds to the decimal value 27.

Example 3:
Input: n = 12
Output: 505379714
Explanation: The concatenation results in "1101110010111011110001001101010111100".
The decimal value of that is 118505380540.
After modulo 10^9 + 7, the result is 505379714.

Constraints:
1 <= n <= 105
 * */
class Solution {
    /*
    * solution: Time:O(n*log(num)), Space:O(1)
    * n = 3
    1 - 1
    2 - 10
    3 - 11
    123 -> 11011 -->
    (1 * 2^4) + (1 * 2^3 + 0 * 2 ^ 2) + (1 * 2^1 + 1 * 2^0)
    (1 * 2^4) + (2 * 2^2 + 0 * 2 ^ 2) + (2 * 2^0 + 1 * 2^0)
    (1 * 2^4) + (2 + 0) * 2 ^2  + (2 + 1)* 2^0
    (1)* 2^4 + (2) * 2^2  + (3)* 2^0
    ((1)* 2^4 + (2) * 2^2)  + (3)* 2^0
    ((1)* 2^2 + (2)) * 2^2)  + (3)* 2^0
    (4 + 2) * 2^2 + 3
    24 + 3
    27
    * */
    fun concatenatedBinary(n: Int): Int {
        var result = 0L
        val mod = 1000000007
        for (i in 1..n) {
            //get the length of binary string of each number
            var num = i
            var len = 0
            while (num > 0) {
                len++
                num = num shr 1
            }
            result = ((result.shl(len))+i) % mod
        }
        return result.toInt()
    }
}

 

posted @ 2021-09-01 16:19  johnny_zhao  阅读(75)  评论(0编辑  收藏  举报