From 35d0023efdb18f02cacabe382372632e82042a73 Mon Sep 17 00:00:00 2001 From: matbol <48551028+matbol@users.noreply.github.com> Date: Wed, 23 Dec 2020 13:44:00 +0100 Subject: [PATCH 1/2] Without reverse --- bit_manipulation/addBin.cpp | 67 ++++++++++++++----------------------- 1 file changed, 26 insertions(+), 41 deletions(-) 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 Date: Mon, 28 Dec 2020 16:35:50 +0100 Subject: [PATCH 2/2] Update next_power_of_2.cpp --- bit_manipulation/next_power_of_2.cpp | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/bit_manipulation/next_power_of_2.cpp b/bit_manipulation/next_power_of_2.cpp index 10fc903..4859c98 100644 --- a/bit_manipulation/next_power_of_2.cpp +++ b/bit_manipulation/next_power_of_2.cpp @@ -4,17 +4,10 @@ #include 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()