67. 二进制求和 Java版
作者:互联网
class Solution {
public String addBinary(String a, String b) {
if(a==null||a.length()==0)
return b;
if(b==null||b.length()==0)
return a;
StringBuilder stb=new StringBuilder();
int i=a.length()-1;
int j=b.length()-1;
int c=0;
while(i>=0||j>=0){
if(i>=0)
c+=a.charAt(i--)-'0';
if(j>=0)
c+=b.charAt(j--)-'0';
stb.append(c%2);
c>>=1;
}
String res=stb.reverse().toString();
return c>0 ? '1'+res:res;
}
}
public class HelloWorld {
public static void main(String []args) {
System.out.println("Hello World!");
String res=addBinary("110010011","11");
System.out.println(res);
}
static String addBinary(String a, String b) {
if(a==null||a.length()==0)
return b;
if(b==null||b.length()==0)
return a;
StringBuilder stb=new StringBuilder();
int i=a.length()-1;
int j=b.length()-1;
int c=0;
while(i>=0||j>=0){
if(i>=0)
c+=a.charAt(i--)-'0';
if(j>=0)
c+=b.charAt(j--)-'0';
stb.append(c%2);
System.out.println(stb.reverse());
System.out.print(c+" ");
c>>=1;
System.out.println(c);
System.out.println();
}
String res=stb.reverse().toString();
return c>0 ? '1'+res:res;
}
}
标签:Java,String,stb,二进制,res,System,int,length,67 来源: https://blog.csdn.net/CSDNer_zry/article/details/120606966