[LeetCode]--67. Add Binary
来源:互联网 发布:打淘宝客服要话费吗 编辑:程序博客网 时间:2024/05/01 06:24
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
二进制算法,加上对字符串的处理。
public String addBinary(String a, String b) { if ((a.length() == 0 || a.isEmpty()) && (b.length() == 0 || b.isEmpty())) return null; if (a.length() == 0 || a.isEmpty()) return b; if (b.length() == 0 || b.isEmpty()) return a; int i = a.length() - 1, j = b.length() - 1, sum, m = 0; int[] temp = new int[Math.max(a.length(), b.length()) + 1]; int k = temp.length; while (i >= 0 && j >= 0) { sum = a.charAt(i) - '0' + b.charAt(j) - '0' + m; temp[--k] = sum % 2; m = sum / 2; i--; j--; } while (i >= 0) { sum = a.charAt(i) - '0' + m; temp[--k] = sum % 2; m = sum / 2; i--; } while (j >= 0) { sum = b.charAt(j) - '0' + m; temp[--k] = sum % 2; m = sum / 2; j--; } if (m == 1) temp[0] = 1; String str = ""; for (int l = 0; l < temp.length; l++) { if (l == 0 && temp[l] == 0) continue; str = str.concat(Integer.toBinaryString(temp[l])); } return str; }
看了一下专业人士写的,跟我差不太多,还是有一点可以借鉴。如果没必要保持原有的字符串啥的,我们可以对不知道大小的情况先进行排序,就知道哪个遍历先完了。而且字符串实现了+号的重载,没必要用concat方法的其实,直接用加号就行。
public String addBinary(String a, String b) { if(a.length() < b.length()){ String tmp = a; a = b; b = tmp; } int pa = a.length()-1; int pb = b.length()-1; int carries = 0; String rst = ""; while(pb >= 0){ int sum = (int)(a.charAt(pa) - '0') + (int)(b.charAt(pb) - '0') + carries; rst = String.valueOf(sum % 2) + rst; carries = sum / 2; pa --; pb --; } while(pa >= 0){ int sum = (int)(a.charAt(pa) - '0') + carries; rst = String.valueOf(sum % 2) + rst; carries = sum / 2; pa --; } if (carries == 1) rst = "1" + rst; return rst; }
0 0
- [LeetCode]67.Add Binary
- LeetCode --- 67. Add Binary
- [Leetcode] 67. Add Binary
- [leetcode] 67.Add Binary
- 【leetcode】67. Add Binary
- [leetcode] 67.Add Binary
- [leetcode] 67. Add Binary
- 【Leetcode】67. Add Binary
- 67. Add Binary LeetCode
- 【LeetCode】67. Add Binary
- leetcode--67. Add Binary
- leetcode 67. Add Binary
- LeetCode 67. Add Binary
- LeetCode *** 67. Add Binary
- leetcode 67. Add Binary
- 【leetcode】67.Add Binary
- LeetCode 67. Add Binary
- LeetCode-67.Add Binary
- 5-特权级
- log4j配置示例&Spring集成log4j
- Division (斜率dp)
- 面试题:两个对象值相同(x.equals(y) == true),但却可有不同的hash code,这句话对不对?
- 2016四川省赛 Floyd-Warshall
- [LeetCode]--67. Add Binary
- Linux 时钟模块分析2
- |洛谷|动态规划|P1156 垃圾陷阱
- framebuffer简介与应用
- Cache-Control no-cache与max-age=0的区别
- 机器学习笔记(十五)——HMM序列问题和维特比算法
- HDU 2031 进制转换
- BZOJ2093[Poi2010] Frog
- 【Maven实战】05 依赖