Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Example program
- #include <iostream>
- #include <string>
- #include <cmath>
- using namespace std;
- unsigned GetNumberOfDigits (unsigned i)
- {
- return i > 0 ? (int) log10 ((double) i) + 1 : 1;
- }
- void reverseStr(string& str)
- {
- int n = str.length();
- // Swap character starting from two
- // corners
- for (int i = 0; i < n / 2; i++)
- swap(str[i], str[n - i - 1]);
- }
- string decimalToBinary(int input, int len=0)
- {
- len=1+floor(log10(input));//c++ code lib (cmath)
- int temp = input;
- string output = "";
- while(1)
- {
- if(temp==1)
- {
- output +="1";
- break;
- }
- int tempBin = temp % 2;
- char tempChar = tempBin+48;
- output += tempChar;
- temp = temp / 2;
- len = GetNumberOfDigits(temp);
- }
- reverseStr(output);
- return output;
- }
- int main()
- {
- int n = 1001;
- string outputNumber = decimalToBinary(n);
- cout << "OUTPUT " << outputNumber << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement