简体   繁体   English

将十进制更改为二进制并用非常大的数字计算其中的数字

[英]Changing Decimal to Binary and Counting the ones in it with really really Large numbers

need to change decimals to binary from A to B and counting the ones in each number i turn into binary did all these except the time taken to do this of large numbers takes forever :D Here's my code:需要将十进制从 A 变为 B 并计算每个我变成二进制的数字中的那些,除了执行大数字所需的时间永远需要永远:D 这是我的代码:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string IntToBinary(long long number){
    string empty = "";
    while (number >= 1)
        if (number % 2 == 0){
            empty += '0';
            number /= 2;
        }
        else{
            empty += '1';
            number--;
            number /= 2;
        }
        reverse(empty.begin(), empty.end());
        return empty;
}

int main(){
long long A, B, count = 0;
while (cin >> A >> B){
    string temp;
    for (int i = A; i <= B; i++){
        temp = IntToBinary(i);
        for (int j = 0; j < temp.length(); j++){
            if (temp[j] == '1')
                count++;
        }
    }
    cout << count << endl;
    count = 0;
}
cin.get();
getchar();
return 0;
}

when i try to enter a large two numbers like 1000000000000000 10000000000000000 or 9007199254740992 9007199254740992 it takes forever =D当我尝试输入像 1000000000000000 10000000000000000 或 9007199254740992 9007199254740992 这样的大两个数字时,它需要永远=D

while (number >= 1)
    if (number % 2 == 0){
        empty += '0';
        number /= 2;
    }
    else{
        empty += '1';
        number--;
        number /= 2;
    }

You can write that much more simply, without the if/else , as follows:您可以更简单地编写,无需if/else ,如下所示:

while (number >= 1)
{
    empty += (number % 2)+'0';
    number /= 2;
}

and you should count the 1's during this loop, not in a second loop.并且您应该在此循环中计算 1,而不是在第二个循环中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM