diff --git a/bit_manipulation/addBin.cpp b/bit_manipulation/addBin.cpp index 26bca95..8b3fa2b 100644 --- a/bit_manipulation/addBin.cpp +++ b/bit_manipulation/addBin.cpp @@ -2,49 +2,34 @@ * 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; +#include +std::string addBinary(std::string & string1, std::string & string2){ + int temp1=0, temp2=0; + int i=0; + std::string temp_string; + + for(i; i int next_power_of_2( int num ) { - //already a power of 2 - if (num && !(num & (num-1))) { - return num; + if(num & (1<<0)){ + return num+1; } - //count till msb set bit - int count = 0; - while ( num != 0 ) { - num >>= 1; - count++; - } - return (1 << count); + return num; } int main()