Skip to content

Without reverse #185

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 26 additions & 41 deletions bit_manipulation/addBin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,34 @@
* Add two binary numbers represented as string.
*
*/
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

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 <iostream>

std::string addBinary(std::string & string1, std::string & string2){
int temp1=0, temp2=0;
int i=0;
std::string temp_string;

for(i; i<string1.size(); ++i){
temp1 |= ((string1[i] - '0') << (string1.size() - i - 1));
}
for(i=0; i<string2.size(); ++i){
temp2 |= ((string2[i] - '0') << (string2.size() - i - 1));
}
temp1 += temp2;
int count = string1.size();
for(i=0; i<count+1; ++i){
if(temp1 & (1<<count-i) && temp1 < (1<<count-i)){
break;
}
else if(temp1 & (1<<count-i)){
temp_string.append("1");
}
else{
temp_string.append("0");
}
}
return temp_string;
}

int main()
Expand Down
13 changes: 3 additions & 10 deletions bit_manipulation/next_power_of_2.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,10 @@
#include <iostream>

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()
Expand Down