Problem:
輸入一數字n,將1到n的binary concatenate在一起後,輸出最後的數字。由於數字太大,所以取10^9+7的餘數。
Example 1:
Input: n = 1 Output: 1 Explanation: "1"
Example 2:
Input: n = 3 Output: 27 Explanation: "11011"
Example 3:
Input: n = 12 Output: 505379714 Explanation: "1101110010111011110001001101010111100".
Programming Language: C++
Execution time: 256 ms
Solution:
先將數字reverse,再串起來
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Solution { public: int concatenatedBinary(int n) { const int modulo = 1000000007; long long int result = 0; for(int num = 1;num <= n;num++){ int count = 0; int binary = num, reverse_binary = 0; while(binary){ reverse_binary = (reverse_binary << 1) | (binary & 0x01); binary >>= 1; count++; } while(count--){ result = (result << 1) | (reverse_binary & 0x01); reverse_binary >>= 1; } result %= modulo; } return result; } }; |