码迷,mamicode.com
首页 > 其他好文 > 详细

1680. Concatenation of Consecutive Binary Numbers

时间:2021-01-29 11:41:16      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:nbsp   mod   toc   简单方法   out   简单   char   value   dbi   

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 109 + 7, the result is 505379714.

 

Constraints:

  • 1 <= n <= 105
class Solution {
    public int concatenatedBinary(int n) {
        int mod = 1_000_000_007;
        int sum = 0;
        for(int i = 1; i <= n; i++) {
            String cur = Integer.toBinaryString(i);
            for(char c : cur.toCharArray()) {
                int val = (c == ‘0‘) ? 0 : 1;
                sum = ((sum) * 2 % mod + val) % mod;
            }
        }
        return sum;
    }
}

简单方法,就一个一个算,但是每个数的每一位sum都要*2更新,也要mod

 

1680. Concatenation of Consecutive Binary Numbers

标签:nbsp   mod   toc   简单方法   out   简单   char   value   dbi   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14338835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!