- public class AddBinayNumber {
- public static void main(String[] args) {
- String s1 = "11";
- String s2 = "1";
- String sum = addTwoBinaryNumber(s1, s2);
- System.out.println(sum);
- }
- private static String addTwoBinaryNumber(String s1, String s2) {
- StringBuilder sb = new StringBuilder();
- int p1 = s1.length() - 1;
- int p2 = s2.length() - 1;
- int carry = 0;
- while (p1 >= 0 || p2 >= 0) {
- int sum = carry;
- if (p1 >= 0) {
- char ch1 = s1.charAt(p1);
- sum = sum + ch1 - '0';
- p1--;
- }
- if (p2 >= 0) {
- char ch2 = s2.charAt(p2);
- sum = sum + ch2 - '0';
- p2--;
- }
- carry = sum >> 1;
- sum = sum & 1;
- sb.append(sum == 0 ? '0' : '1');
- }
- if (carry > 0) {
- sb.append('1');
- }
- sb.reverse();
- return sb.toString();
- }
- }
Monday, April 16, 2018
How to add two binary numbers ?
Subscribe to:
Post Comments (Atom)
How to run standalone mock server on local laptop
Please download the standalone wiremock server from Direct download section at the bottom of the page. Download and installation Feel fre...
-
Cryptography or cryptology (from Ancient Greek: kryptós "hidden, secret"; graphein, "to write") is the practice and stu...
-
Problem statement: what would be the better option to choose between char[] array and String. Answer: Character array i.e. char[] over ...
-
Please download the standalone wiremock server from Direct download section at the bottom of the page. Download and installation Feel fre...
No comments:
Post a Comment