diff --git a/bit_manipulation/addBin.cpp b/bit_manipulation/addBin.cpp new file mode 100644 index 0000000..26bca95 --- /dev/null +++ b/bit_manipulation/addBin.cpp @@ -0,0 +1,57 @@ +/* + * Add two binary numbers represented as string. + * + */ +#include +#include +#include +#include + +std::string addBinary( const std::string & str1, const std::string & str2 ) +{ + std::string s1 = ( str1.length() > str2.length() ? str1 : str2 ); + std::string s2 = ( str1.length() > str2.length() ? str2 : str1 ); + int diff = s1.length() - s2.length(); + std::stringstream ss; + while(diff) { + ss << "0"; + --diff; + } + s2 = ss.str() + s2; + std::cout << s1 << std::endl; + std::cout << s2 << std::endl; + ss.str(std::string()); + int i = s1.length() - 1; + int carry = 0; + while ( i >= 0 ) { + int x = ( s1[i] - '0') + ( s2[i] - '0') + carry; + if ( x == 2 ) { + x = 0; + carry = 1; + } + else if ( x == 3 ) { + x = 1; + carry = 1; + } else { + carry = 0; + } + ss << x; + --i; + } + if ( carry == 1 ) + ss << carry; + + std::string result = ss.str(); + std::reverse(result.begin(), result.end()); + return result; + +} + +int main() +{ + std::string str1("1010"); + std::string str2("1011"); + std::cout << "Addition of " << str1 << " and " << str2 << " is :" << addBinary(str1, str2) << std::endl; + return 0; + +} diff --git a/bit_manipulation/power_of_2.cpp b/bit_manipulation/power_of_2.cpp new file mode 100644 index 0000000..2b656c3 --- /dev/null +++ b/bit_manipulation/power_of_2.cpp @@ -0,0 +1,23 @@ +/* + * Given a number, determine if its power of 2 using bit manipulation in O(1) + */ + +#include + +bool powerOfTwo( int n ) +{ + return (n > 0 && !( n & ( n - 1 ) )); +} + +int main() +{ + int n; + std::cout << "Enter a number :"; + std::cin >> n; + if ( powerOfTwo(n) ) { + std::cout << n << " is power of 2\n"; + } else { + std::cout << n << " is not power of 2\n"; + } + return 0; +}