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

Java calculates the sum of binary strings

王林
Release: 2020-12-01 14:45:18
forward
2579 people have browsed it

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();
        }
    }
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template