leetcode Add Binary
来源:互联网 发布:好的淘宝文案 编辑:程序博客网 时间:2024/06/03 18:27
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题目本身还是比较简单的,就是二进制加法,不过写程序的时候发现自己对字符串的api还是有点生疏,贴出来以便复习用吧~注意一下进位的取值就可以了。
public String addBinary(String a, String b) { String res=new String(); int exceed = 0; int bits=0; int indexa = a.length() - 1, indexb = b.length() - 1; while (indexa >= 0 && indexb >= 0) { int result = a.charAt(indexa)-'0'+b.charAt(indexb)-'0'+exceed; bits=result%2; exceed=result/2; res=""+bits+""+res; indexa--; indexb--; } while(indexa>=0) { int result = exceed + a.charAt(indexa)-'0'; bits=result%2; exceed=result/2; res=""+bits+""+res; indexa--; } while(indexb>=0) { int result = exceed + b.charAt(indexb)-'0'; bits=result%2; exceed=result/2; res=""+bits+""+res; indexb--; } if(exceed==1) res=""+exceed+""+res; StringBuffer str=new StringBuffer(); return res;}
0 0
- LeetCode: Add Binary
- [Leetcode] Add Binary
- LeetCode Add Binary
- Leetcode: Add Binary
- [Leetcode] Add Binary
- LeetCode : Add Binary
- LeetCode Add Binary
- [LeetCode] Add Binary
- leetcode 58: Add Binary
- leetcode Add Binary
- [LeetCode] Add Binary
- 【leetcode】Add Binary
- [LeetCode]Add Binary
- [leetcode]Add Binary
- LeetCode-Add Binary
- [leetcode] Add Binary
- LeetCode - Add Binary
- leetcode:Add Binary
- <<设计模式>>读书笔记------单例模式
- git笔记
- Junit4中的新断言assertThat的是用方法
- Linux常用命令快捷键使用
- Gradle 如何使用Android Studio把自己的Android library分享到jCenter和Maven Central
- leetcode Add Binary
- HDU 4608 I-number(YY)
- C++ Boost 解析JSON
- c++:函数传指针(void * xx)、传引用(void & xx)和传指针的引用(void *& xx)
- 在java中使用FreeMark导出数据到excel表格
- UVA 1635 Irrelevant Elements
- Insight 根据advisor生成Proxy过程 | AOP调用性能解疑
- 4种方法让SpringMVC接收多个对象
- 条款08 别让异常逃离析构函数