From 5b0262b2a504d57485f122abece2281ce0049afd Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 24 Oct 2018 16:14:03 -0500 Subject: [PATCH] Added intToBinary.cpp file, this code prints the binary representation of a given integer --- Algorithms/intToBinary.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Algorithms/intToBinary.cpp diff --git a/Algorithms/intToBinary.cpp b/Algorithms/intToBinary.cpp new file mode 100644 index 000000000..434c7fd27 --- /dev/null +++ b/Algorithms/intToBinary.cpp @@ -0,0 +1,30 @@ +#include + +using namespace std; + +int stringToInt(string s) { + int p = 1; + int n = 0; + for(int i = s.size()-1; i >= 0; i --) { + n += (s[i] - '0') * p; + p *= 10; + } + return n; +} + +string intToBinary(int n) { + string bin = ""; + while(n > 0) { + bin = (char)((n % 2)+'0') + bin; + n /= 2; + } + return bin; +} + +int main(int argc, char** argv) { + /*cout<