- 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)
Blueprint for self-improvement
To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...
-
Problem statement: There is a colony of 8 cells arranged in a straight line where each day every cell competes with its adjacent cells(neig...
-
Problem statement: Given an array of positive or negative integer. How will you write an algorithm to find out the largest element in the ...
-
Problem statement: Write a function to print spiral order traversal of a tree. For example. Input - 10 J H I A C D F E B G...
No comments:
Post a Comment