67. Add Binary
来源:互联网 发布:如何入门数据分析师 编辑:程序博客网 时间:2024/06/06 06:34
**题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
Subscribe to see which companies asked this question
**
思想:String ->Char->int->String
public class Add_Binary { /* main function to solve the problem*/ public String addBinary(String a,String b) { int length_a = 0; int length_b = 0; length_a = getlength(a); length_b = getlength(b); return judge(a,b,length_a,length_b); } /* get the String's length*/ public int getlength(String x) { int length = x.length(); return length; } /* judge String a and String b and use function*/ public String judge(String a,String b,int x,int y) { int max = Math.max(x,y); int min = Math.min(x,y); int carries = 0; String result = ""; int j = 0 ; if(x==0||a==null) return b; else if(y==0||b==null) return a; else { //when a.length>0 and b.length>0 while(max>0&&min>0) { int p = a.charAt(a.length()-j-1)-'0'+b.charAt(b.length()-j-1)-'0'+carries; result = p%2+ result; carries = p/2; j++; max--; min--; } //when a.length=min and it can't use the top function to solve problem; if(j==a.length()) { while(j!=b.length()) { int p = b.charAt(b.length()-j-1)-'0'+carries; result = p%2+ result; carries = p/2; j++; } } //when b.length=min and it can't use the top function to solve problem; else if(j==b.length()) { while(j!=a.length()) { int p = a.charAt(a.length()-j-1)-'0'+carries; result = p%2+ result; carries = p/2; j++; } } //At the Last,if carries == 1 ,we must put "1" in front of it; if(carries==1) result = "1"+result; return result; } } public static void main(String[] args) { Add_Binary newbinary = new Add_Binary(); System.out.println(newbinary.addBinary("1101", "11")); }}
0 0
- [LeetCode]67.Add Binary
- LeetCode --- 67. Add Binary
- [Leetcode] 67. Add Binary
- [leetcode] 67.Add Binary
- 67. Add Binary
- 【leetcode】67. Add Binary
- 67. Add Binary
- [leetcode] 67.Add Binary
- [leetcode] 67. Add Binary
- 67. Add Binary
- 67. Add Binary
- 【Leetcode】67. Add Binary
- 67. Add Binary
- 67. Add Binary LeetCode
- 67. Add Binary
- 【LeetCode】67. Add Binary
- 67. Add Binary
- 67. Add Binary
- CSS代码中-webkit,-moz,-o,-ms含义
- Ubuntu下载Android源码
- 网络(Java核心技术卷Ⅱ)
- python字符串处理
- 关于Div的宽度与高度的100%设定
- 67. Add Binary
- Android中的Adapter封装
- Zeppelin安装文档
- UE4:关闭自动曝光
- Error getting nested result map values for 'user_inf'. Cause: java.sql.SQLException: Cannot convert
- sigsuspend()函数 解释
- Android酷炫的加载动画
- C# 编程遇到An object reference is required for the non-static field, method, or property错误
- Hadoop完全分布式+HA配置