Home >Java >Javagetting Started >Java calculates the sum of binary strings

Java calculates the sum of binary strings

王林
王林forward
2020-12-01 14:45:182590browse

Java calculates the sum of binary strings

Purpose:

Find the sum of binary strings.

(Recommended tutorial: java teaching video)

Title introduction:

Give you two binary strings, return their sum (using binary express).

The input is a non-empty string and only contains the numbers 1 and 0.

Example 1:

Input: a = “11”, b = “1”
Output: “100”

Example 2 :

Input: a = “1010”, b = “1011”
Output: “10101”

Prompt:

Each The string consists only of the characters '0' or '1'.
1 If the string is not "0", it does not contain leading zeros.

import java.util.Scanner;public class text1 {
    public static void main(String[] a){
        Scanner imput=new Scanner(System.in);
        System.out.println("请输入两个二进制数:");
        String a1,a2,a3;
        a1=imput.next();
        a2=imput.next();
        a3=Solution(a1,a2);
        System.out.println(a3);
    }
        public static String Solution(String a, String b) {
            StringBuilder ans = new StringBuilder();
            int ca = 0;
            for(int i = a.length() - 1, j = b.length() - 1;i >= 0 || j >= 0; i--, j--) {
                int sum = ca;
                sum += i >= 0 ? a.charAt(i) - '0' : 0;
                sum += j >= 0 ? b.charAt(j) - '0' : 0;
                ans.append(sum % 2);
                ca = sum / 2;
            }
            ans.append(ca == 1 ? ca : "");
            return ans.reverse().toString();
        }
    }

Running results:

Java calculates the sum of binary strings

Related tutorials: java introductory tutorial

The above is the detailed content of Java calculates the sum of binary strings. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete