LeetCode - Add Binary
来源:互联网 发布:css 开发工具 知乎 编辑:程序博客网 时间:2024/06/16 22:35
https://leetcode.com/problems/add-binary/
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) { char[] sa = a.toCharArray(); char[] sb = b.toCharArray(); int i=sa.length-1; int j = sb.length-1; char[] longer = i>=j? sa:sb; int left = i>=j? i:j; int carry = 0; while(i>=0 && j>=0){ int val = (sa[i]-'0') + (sb[j]-'0') + carry; longer[left] = (char)(val%2 + '0'); carry = val/2; i--; j--; left--; } while(left>=0){ int val = (longer[left]-'0') + carry; longer[left] = (char)(val%2 + '0'); carry = val/2; left--; } String rst = new String(longer); if(carry>0) rst = "1" + rst; return rst; }
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
- OpenGL学习笔记-2015.3.24——transform feedback缓存&粒子系统示例分析
- jQuery源码学习(版本1.11)-整体架构
- 插件笔记_CryptoPlayerPrefs-1.3.3
- search - fibonacci search
- LeetCode - Divide Two Integers
- LeetCode - Add Binary
- C++之强制类型转换原理
- 火狐、IE、Chrome已进入三国时代
- Android开发之Intent
- LeetCode - Factorial Trailing Zeroes
- LeetCode - Excel Sheet Column Title
- a标签页面内跳转 链接被后台地址过滤器拦截
- LeetCode - Excel Sheet Column Number
- Make Games With Us Tutorials