zoukankan      html  css  js  c++  java
  • 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()
        }
    }
  • 相关阅读:
    成为优秀程序员的101条建议(3)
    shell字符串的用法
    Centos yum国内源及配置含义
    go自动补全
    shell中空格的使用;空格替换;通配符
    shell自动补全功能:bash和zsh;zsh启动优化
    Mac下的命令行自动补全功能
    mac环境下intellij的自定义配置文件位置
    vim中delete(backspace)键不能向左删除
    一个性能较好的JVM参数配置
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15215138.html
Copyright © 2011-2022 走看看