Monday, April 16, 2018

How to add two binary numbers ?


  1. public class AddBinayNumber {

  2. public static void main(String[] args) {
  3. String s1 = "11";
  4. String s2 = "1";
  5. String sum = addTwoBinaryNumber(s1, s2);
  6. System.out.println(sum);
  7. }

  8. private static String addTwoBinaryNumber(String s1, String s2) {
  9. StringBuilder sb = new StringBuilder();
  10. int p1 = s1.length() - 1;
  11. int p2 = s2.length() - 1;
  12. int carry = 0;
  13. while (p1 >= 0 || p2 >= 0) {
  14. int sum = carry;
  15. if (p1 >= 0) {
  16. char ch1 = s1.charAt(p1);
  17. sum = sum + ch1 - '0';
  18. p1--;
  19. }
  20. if (p2 >= 0) {
  21. char ch2 = s2.charAt(p2);
  22. sum = sum + ch2 - '0';
  23. p2--;
  24. }
  25. carry = sum >> 1;
  26. sum = sum & 1;
  27. sb.append(sum == 0 ? '0' : '1');
  28. }
  29. if (carry > 0) {
  30. sb.append('1');

  31. }
  32. sb.reverse();
  33. return sb.toString();
  34. }
  35. }
Output: 100

No comments:

Post a Comment

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