Add Binary LeetCode Java

描述
Given two binary strings, return their sum (also a binary string).
For example,

a = "11"

b = "1"

Return ”100”

分析

代码

 1 public class AddBinary {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5         String str1="111";
 6         String str2="1";
 7         System.out.println(addBinary (str1,str2));
 8 }
 9     public static String addBinary(String str1,String str2) {
10         if(str1==""||str2=="") return null;
11 //        int a1=Integer.parseInt(str1,2);
12 //        int a2=Integer.parseInt(str2,2);
13         
14         char[] ch1=str1.toCharArray();
15         char[] ch2=str2.toCharArray();
16         int a1=0,a2=0;
17         for(int i=0;i<ch1.length;i++) {
18             a1+=Math.pow(2, i)*(str1.charAt(ch1.length-1-i)-'0');
19         }
20         
21         for(int i=0;i<ch2.length;i++) {
22             a2+=Math.pow(2, i)*(str2.charAt(ch2.length-1-i)-'0');
23         }
24         int num=a1+a2;
25         String result=Integer.toBinaryString(num);
26         return result;
27    }
28     
29 }

 方法二

 1 public static String addBinary(String str1, String str2) {
 2         if (str1 == "" || str2 == "")
 3             return null;
 4 int n = Math.max(str1.length(), str2.length());
 5 
 6         char[] res = new char[n];
 7         int flag = 0;
 8         int a1 = 0, a2 = 0;
 9         for (int i = 0; i < n; i++) {
10             if (i < str1.length())
11                 a1 = str1.charAt(str1.length() - 1 - i) - '0';
12             else
13                 a1 = 0;
14 
15             if (i < str2.length())
16                 a2 = str2.charAt(str2.length() - 1 - i) - '0';
17             else
18                 a2 = 0;
19 
20             // if ((a1 + a2 + flag)%2==1) {
21             // res[n - 1 - i] ='1';
22             // flag = (a1 + a2 + flag)/2;
23             // }
24             // else if((a1 + a2 + flag)%2==0){
25             // res[n - 1 - i] = '0';
26             // flag = (a1 + a2 + flag)/2;
27             // }
28 
29             if ((a1 + a2 + flag) == 3) {
30                 res[n - 1 - i] = '1';
31                 flag = 1;
32             }
33 
34             else if (a1 + a2 + flag == 2) {
35                 res[n - 1 - i] = '0';
36                 flag = 1;
37 
38             } else if (a1 + a2 + flag == 1) {
39                 res[n - 1 - i] = '1';
40                 flag = 0;
41 
42             } else {
43                 res[n - 1 - i] = '0';
44                 flag = 0;
45             }
46         }
47 
48         return (flag == 0) ? new String(res) : "1" + new String(res);
49         // return result;
50     }
原文地址:https://www.cnblogs.com/ncznx/p/9178775.html