From f400b23dcc8a17efd35d9b950ec37d2415a73431 Mon Sep 17 00:00:00 2001 From: Himanshu Singh Date: Mon, 7 Oct 2024 10:33:18 +0530 Subject: [PATCH] new update --- binaryAdd.class | Bin 0 -> 1750 bytes binaryAdd.java | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 binaryAdd.class create mode 100644 binaryAdd.java diff --git a/binaryAdd.class b/binaryAdd.class new file mode 100644 index 0000000000000000000000000000000000000000..5716dcd596b10516b1a4d8d46b0402b18e62c26a GIT binary patch literal 1750 zcmaJ>TT|Oc6#f=VmhFgeRRRenP7B0<6Q?&f#R(0#p`kS-t*I$ZFIlV&D9DmWS~KN6 zKcX|q^tG>TW@?JB2>P3}_~F z#2E%3^L?Ioxwn(QxBXbuBt!hB<2iDXA(ox38b~mlKL%A~;CMUBO~N+SW@T;Z%6J%3Re|;$iy&4Xrs2vgC#PlWmjiQN}FZk9M01YZ#0BwGfdD< z`G3q8)roNv7jTim2*kb!Lcwq``}z}U6O*{akdXc>4@Y|(DH^!UFcjHtO2^GtYTWZg zki?sqGB9mo23NY{JqV?!GxRwggVpxh@$;)*qbbRf;C1pigIPuW9K%?)CuFv&EaXgF z#WkYLZxTPp%I*{WuaqTloua+tNfBfoIYB5h+m6SBgN)a#Z;N0dlfv70$H2QL-a~<5 zB#MPRI-!I?Zzz>yqvK9g3vFVGvsLBr4HF+kgn8n7S#~^;K#?-jHXMqY@7bp<-@>AS z4^7<05<{}>*pf{dO>)~_j{Ib}(ZlAcY!^?bvpB4Z*~CYDh+cDjRajcdw@C~r3f3cvH~6+oEBzJ8 zYkORNVl^?38W#5;f40vNr$X(wK6ZnFv zrP8ct{72nHhYJ}t5XWW;Ut-I^SBjAb3{%G!#_{(3J&|wcvrW z;9G|2Q!({&)xblB$=5@vyR_rNW!$1}sGb-o&4|;tOtUmeMpBs3~TgN+X|Xg zMNMM`{gdVf$;L|34yeYZfMQ)QfLp096d(JL!CAw!BOskHEDQYt_l#(lC^)tft;d4|-CdivA{WtJ6%~CY_hN9va F{}=x^u!{fy literal 0 HcmV?d00001 diff --git a/binaryAdd.java b/binaryAdd.java new file mode 100644 index 0000000..a2b963a --- /dev/null +++ b/binaryAdd.java @@ -0,0 +1,40 @@ +import java.util.Scanner; + +public class binaryAdd { + + // Method to add two binary numbers + public static String addBinary(String a, String b) { + StringBuilder result = new StringBuilder(); // To store the result + int i = a.length() - 1, j = b.length() - 1, carry = 0; // Index pointers and carry initialization + + // Loop through both strings from right to left + while (i >= 0 || j >= 0 || carry > 0) { + int sum = carry; // Start with carry from the last addition + + if (i >= 0) sum += a.charAt(i--) - '0'; // Convert char to int and add + if (j >= 0) sum += b.charAt(j--) - '0'; + + result.append(sum % 2); // Append the result of sum modulo 2 (binary addition) + carry = sum / 2; // Update the carry for the next position + } + + return result.reverse().toString(); // Reverse and return the result + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + // Input two binary numbers + System.out.print("Enter first binary number: "); + String binary1 = scanner.nextLine(); + + System.out.print("Enter second binary number: "); + String binary2 = scanner.nextLine(); + + // Output the result of binary addition + String result = addBinary(binary1, binary2); + System.out.println("Sum of binary numbers: " + result); + + scanner.close(); + } +}