Problem
Carl is right now the happiest child in the world: he has just learned this morning what the binary system is. He learned, for instance, that the binary representation of a positive integer k is a string a[n], a[n-1], …, a[0] where each a[i] is a binary digit 0 or 1, starting with a[n] = 1, and such that k = \sum{i = 0, n} a[i] * 2^ i. It is really nice to see him turning decimal numbers into binary numbers, and then adding and even multiplying them.
Caesar is Carl’s older brother, and he just can’t stand to see his little brother so happy. So he has prepared a challenge: \Look Carl, I have an easy question for you: I will give you two integers A and B, and you have to tell me how many 1’s there are in the binary representation of all the integers from A to B, inclusive. Get ready”. Carl agreed to the challenge. After a few minutes, he came back with a list of the binary representation of all the integers from 1 to 100. \Caesar, I’m ready”. Caesar smiled and said: \Well, let me see, I choose A = 10^15 and B = 10^16. Your list will not be useful”.
Carl hates loosing to his brother so he needs a better solution fast. Can you help him ?
Input
The input file contains several test cases, each of them as described below.
A single line that contains two integers A and B (1 <= A <= B <= 10^16).
Output
For each test case, output a line with an integer representing the total number of digits 1 in the binary representation of all the integers from A to B, inclusive.
Sample Input
|
|
Sample Output
|
|
Solution
題目描述:
計算 A 到 B 之間的二進制數出現了幾次 1。
題目解法:
將問題轉換成計算 0 到 A 出現了幾次 1,接著討論在相同長度下 1 出現的次數,之後再遞歸求解。
討論的時候,考慮長度為 n 時,每一位的填法,計算要看切割位置的前半和後半數字,詳細查閱代碼。
|
|