-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
80 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
/* | ||
* 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; | ||
|
||
} | ||
|
||
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; | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/* | ||
* Given a number, determine if its power of 2 using bit manipulation in O(1) | ||
*/ | ||
|
||
#include <iostream> | ||
|
||
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; | ||
} |