concatenate binary of first N integers and return decimal value

久未见 提交于 2020-07-16 08:01:45

问题


Example,

N = 3 The first N integers for value 3 is 1, 2, 3

Binary of

1 is 1

2 is 10

3 is 11

Concatenations of N=3 of binary values will be 11011

And the decimal value returned for the binary value 11011 is 27

The code I am using below only works for first integers N<=15

    String input = "";
    for(int i = 1;i<=n;i++) {
        input += (Integer.toBinaryString(i));
    }
    return Integer.parseInt(input,2);

For larger N numbers, any ideas on solving using modulo 10^9 + 7 (since concatenation is large)


回答1:


Note that working with string representation is not necessary (moreover, is not useful after task changing). Look at approach with bitwise arithmetics (Python, but principle is the same)

With new condition concerning modulo 1000000007 we have just add modulo operation to result calculation line at every step, because shift left and or-ing is equivalent to multiplication by power of two and adding, these operations are obeyed to equivalence relations for modulo properties. Note that intermediate results don't exceed 1000000007*n, so long type is suitable here for reasonable n values.

n = 100  
size = 0   #bit length of addends
result = 0   # long accumulator
for i in range(1, n + 1):    
    if i & (i - 1) == 0:    #for powers of two we increase bit length
        size += 1
    result = ((result << size) | i) % 1000000007   #shift accumulator left and fill low bits with new addend
print(result)

variant without bitwise operations:

pow2 = 1
nextpow = 2
result = 0   # long accumulator
for i in range(1, n + 1):
    if i == nextpow:    #for powers of two we increase bit length
        pow2 = nextpow
        nextpow = nextpow * 2
    result = (result * pow2  + i) % 1000000007  #shift accumulator left and fill low bits with new addend



回答2:


String input = "";

    for(int i = 1;i<=n;i++) {
        input += (Integer.toBinaryString(i));
    }
    return new BigInteger(input, 2);


来源:https://stackoverflow.com/questions/62631840/concatenate-binary-of-first-n-integers-and-return-decimal-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!