首页 > 试题广场 >

二进制求和

[编程题]二进制求和
  • 热度指数:106 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给你两个二进制字符串,返回它们的和(用二进制表示)。

输入为 非空 字符串且只包含数字 1 和 0。
示例1

输入

"11","1"

输出

"100"
import java.util.*;
import java.util.Stack;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 
     * @param a string字符串 
     * @param b string字符串 
     * @return string字符串
     */
    public String addBinary (String a, String b) {
    // write code here
        char[] s1 = a.toCharArray();
        char[] s2 = b.toCharArray();
//之后循环需要长的
        if(s1.length<s2.length){
            char[] temp=s1;
            s1=s2;
            s2=temp;
        }
        String str= "";
        int count =0;
        Stack<Integer> sk1 =new Stack<Integer>();
        Stack<Integer> sk2 =new Stack<Integer>();
        Stack<Integer> sk3 =new Stack<Integer>();
//因为是从右往左加所以要加入栈倒叙
        for(char a1:a.toCharArray()){
            sk2.add(change(a1));
        }
        for(char a2:b.toCharArray()){
            sk3.add(change(a2));
        }
//d=0和d=1的情况可以合并
        for(int i=0;i<s1.length;i++){
            int d=0;
            if(!sk3.isEmpty()){
                d=sk2.pop()+sk3.pop()+count;
            }else{
                d = sk2.pop()+count;
            }
                if(d==2){
                    sk1.add(0);
                    count=1;
                }else if(d==1){
                    sk1.add(1);
                    count=0;
                }else if(d==3){
                    sk1.add(1);
                     count=1;
                }else{
                    sk1.add(0);
                    count=0;
                }
              if(i==s1.length-1){
                if(count==1)sk1.add(1);
            }
        }
        while(!sk1.isEmpty()){
            str+=sk1.pop();
        }
        return str;
    }
   private int change(char ad){
       String s1= String.valueOf(ad);
       int sss= Integer.parseInt(s1);
       return sss;
   }
}
发表于 2021-10-11 15:12:06 回复(0)
import java.util.*;
public class Solution {
    // 二进制字符串求和
    public String addBinary (String a, String b) {
        StringBuilder res = new StringBuilder();
        int i = a.length()-1, j = b.length()-1;
        int carry = 0;
        while (i >= 0 || j >= 0) {
            int val = 0;
            val += carry;
            if (i >= 0) val += a.charAt(i--)-'0';
            if (j >= 0) val += b.charAt(j--)-'0';
            carry = val / 2;
            val %= 2;
            res.insert(0, val);
        }
        if (carry > 0) res.insert(0, carry);
        return res.toString();
    }
}
发表于 2022-07-21 22:08:12 回复(0)
参考合并链表
发表于 2021-03-03 12:02:28 回复(0)