• 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()
        }
    }
  • 相关阅读:
    禅道开源版本安装
    NATAPP内网穿透实现
    nginx部署前端项目
    docker-compose部署微服务
    python编写猜数字游戏
    Linux命令(用户管理、组和时间管理)
    Linux命令(文本编辑器)
    Linux的简单命令(防火墙篇)
    什么是泛型
    spring bean 的作用域之间有什么区别
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15215138.html
Copyright © 2020-2023  润新知