[LeetCode][Java] Add Binary
2015-07-17 11:18
459 查看
题目:
Given two binary strings, return their sum (also a binary string).For example,
a =
"11"
b =
"1"
Return
"100".
题意:
给定两个二进制字符,返回他们的和比如,
a =
"11"
b =
"1"
Return
"100".
算法分析:
填充两个字符串中较短的,之后注意进位的问题,没什么特别的。
AC代码:
public class Solution { public String addBinary(String a, String b) { if(a.length()==0) return b; if(b.length()==0) return a; if(a.equals("0")) return b; if(b.equals("0")) return a; int i=0; int j=0; int newplus=0; String res=""; String newa=""; String newb=""; String finalres=""; int maxlength; maxlength=Math.max(a.length(), b.length()); //用‘0’填充a或者b,使其长度相等 if(a.length()>b.length()) { for(i=0;i<a.length()-b.length();i++) { newb+='0'; } for(i=0;i<b.length();i++) newb+=b.charAt(i); newa=a; } else if(b.length()>a.length()) { for(i=0;i<b.length()-a.length();i++) { newa+='0'; } for(i=0;i<a.length();i++) newa+=a.charAt(i); newb=b; } else { newa=a; newb=b; } maxlength=Math.max(newa.length(), newb.length()); int plus=0; int tem=0; for(i=maxlength-1;i>=0;i--) { if(newa.charAt(i)=='1'&&newb.charAt(i)=='1') { tem=0+plus; plus=1; if(i==0) { newplus=1; maxlength++; } } else if(newa.charAt(i)=='0'&&newb.charAt(i)=='0') { tem=0+plus; plus=0; } else { tem=1+plus; if(tem==2) { tem=0; plus=1; if(i==0) { newplus=1; maxlength++; } } } res+=Integer.toString(tem); } if(newplus==1) res=res+'1'; for(i=res.length()-1;i>=0;i--) finalres+=res.charAt(i); return finalres; } }
相关文章推荐
- java之IO处理
- SpringMVC框架介绍
- Java中有关Null的9件事
- Eclipse搭建SSH
- Eclipse快捷键
- JAVA去掉字符串中的各种奇怪字符
- [LeetCode][Java] Plus One
- Struts+Spring+Hibernate整合
- java Json对象解析
- Spring AOP之Advice
- java中System,Date学习笔记
- java实现基于SMTP发送邮件的方法
- Spring之构造注入与设值注入
- JAVA面试题:69道Spring面试题和答案
- 软件开发架构平台技术之Spring依赖注入
- 软件开发架构平台技术-------Struts2之Web容器对象的使用
- struts2 基于OGNL的类型转换
- Spring操作数据库示例
- JAVA实现顺序表
- java编写一个文件查找器