【Java】Given two binary strings, return their sum
来源:互联网 发布:怎么彻底删除手机数据 编辑:程序博客网 时间:2024/06/05 20:37
/** * Given two binary strings, return their sum (also a binary string). * * For example, a = "11" b = "1" Return "100". * * 2014年10月27日 18:55:23 */public class AddBinary {public static void main(String[] args) {System.out.println(addBinary("1111", "1"));}public static String addBinary(String a, String b) {/** a的长度 */int i = a.length() - 1;/** b的长度 */int j = b.length() - 1;/** a中的字符 */int da = 0;/** b中的字符 */int db = 0;/** 进位 0或1 */int adv = 0;/** * StringBuffer的内部实现方式和String不同,所以StringBuffer在进行字符串处理时,不生成新的对象, * 在内存使用上要优于String类。 * 所以在实际使用时,如果经常需要对一个字符串进行修改,例如插入、删除等操作,使用StringBuffer要更加适合一些。 */StringBuffer result = new StringBuffer();/** 相似部分相加的二进制 */while (i >= 0 && j >= 0) {da = a.charAt(i--) == '0' ? 0 : 1;db = b.charAt(j--) == '0' ? 0 : 1;int d = da + db + adv;result.append(d % 2 == 0 ? '0' : '1');/** 运算符优先级 :带符号右移位运算符优先级高于等于号 */adv = d >> 1;// 进位}if (i >= 0) {// 字符串a比较长while (i >= 0) {da = a.charAt(i--) == '0' ? 0 : 1;int d = da + adv;result.append(d % 2 == 0 ? '0' : '1');adv = d >> 1;}} else if (j >= 0) {// 字符串b比较长while (j >= 0) {db = b.charAt(j--) == '0' ? 0 : 1;int d = db + adv;result.append(d % 2 == 0 ? '0' : '1');adv = d >> 1;}}if (adv == 1) {result.append('1');}/** 反转 */return result.reverse().toString();}}
0 0
- 【Java】Given two binary strings, return their sum
- Vertical Sum in a given Binary Tree
- [Happy DSA] Print all interleavings of given two strings
- Minimum ASCII Delete Sum for Two Strings
- Minimum ASCII Delete Sum for Two Strings
- Find distance between two given keys of a Binary Tree
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- Two Sum Java
- 【Leetcode】two sum JAVA
- Two Sum (Java)
- LeetCode java Two Sum
- Two Sum leetcode Java
- [LeetCode][Java] Two Sum
- [letecode java]Two Sum
- leetcode:Two Sum 【Java】
- Two Sum(Java)
- Two Sum(java)
- SSM框架Web程序的流程(Spring SpringMVC Mybatis)
- error LNK2019: 无法解析的外部符号 __imp__DispatchMessageW@4,该符号在函数 _WinMain@16 中被引用
- 无法将类型为“System.__ComObject”的 COM 对象强制转换为接口类型“Microsoft.VisualStudio.OLE.Interop.IServiceProvider”。
- BOOST库介绍,安装
- JS进阶书籍
- 【Java】Given two binary strings, return their sum
- 【IOS】Ready
- awr报告生成
- CF 390E - Inna and Large Sweet Matrix(TODO)
- pod setup 失败
- HDU2053 Switch Game
- Hibernate-Validation使用简介
- UVa 11064 - Number Theory
- Android重复点击后退,退出app,后台继续运行