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 @   johnny_zhao  阅读(81)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示