Skip to content

Commit 62a9055

Browse files
committed
Day20-bit manipulation problems
1 parent ed8ab95 commit 62a9055

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

bit_manipulation/addBin.cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
* Add two binary numbers represented as string.
3+
*
4+
*/
5+
#include <iostream>
6+
#include <string>
7+
#include <sstream>
8+
#include <algorithm>
9+
10+
std::string addBinary( const std::string & str1, const std::string & str2 )
11+
{
12+
std::string s1 = ( str1.length() > str2.length() ? str1 : str2 );
13+
std::string s2 = ( str1.length() > str2.length() ? str2 : str1 );
14+
int diff = s1.length() - s2.length();
15+
std::stringstream ss;
16+
while(diff) {
17+
ss << "0";
18+
--diff;
19+
}
20+
s2 = ss.str() + s2;
21+
std::cout << s1 << std::endl;
22+
std::cout << s2 << std::endl;
23+
ss.str(std::string());
24+
int i = s1.length() - 1;
25+
int carry = 0;
26+
while ( i >= 0 ) {
27+
int x = ( s1[i] - '0') + ( s2[i] - '0') + carry;
28+
if ( x == 2 ) {
29+
x = 0;
30+
carry = 1;
31+
}
32+
else if ( x == 3 ) {
33+
x = 1;
34+
carry = 1;
35+
} else {
36+
carry = 0;
37+
}
38+
ss << x;
39+
--i;
40+
}
41+
if ( carry == 1 )
42+
ss << carry;
43+
44+
std::string result = ss.str();
45+
std::reverse(result.begin(), result.end());
46+
return result;
47+
48+
}
49+
50+
int main()
51+
{
52+
std::string str1("1010");
53+
std::string str2("1011");
54+
std::cout << "Addition of " << str1 << " and " << str2 << " is :" << addBinary(str1, str2) << std::endl;
55+
return 0;
56+
57+
}

bit_manipulation/power_of_2.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
* Given a number, determine if its power of 2 using bit manipulation in O(1)
3+
*/
4+
5+
#include <iostream>
6+
7+
bool powerOfTwo( int n )
8+
{
9+
return (n > 0 && !( n & ( n - 1 ) ));
10+
}
11+
12+
int main()
13+
{
14+
int n;
15+
std::cout << "Enter a number :";
16+
std::cin >> n;
17+
if ( powerOfTwo(n) ) {
18+
std::cout << n << " is power of 2\n";
19+
} else {
20+
std::cout << n << " is not power of 2\n";
21+
}
22+
return 0;
23+
}

0 commit comments

Comments
 (0)