LeetCode_67---Add Binary
来源:互联网 发布:syslog 端口号 编辑:程序博客网 时间:2024/05/21 18:11
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
翻译:
Code:
/** * */package From61;import java.util.Arrays;/** * @author MohnSnow * @time 2015年6月29日 下午1:40:25 * */public class LeetCode67 {/** * @param argsmengdx * -fnst *///360msAC----一次性提交通过public static String addBinary(String a, String b) {int a_len = a.length();int b_len = b.length();if (a_len == 0) {return b;} else if (b_len == 0) {return a;}int len = Math.max(a_len, b_len);int[] temp = new int[len];int tempInt = 0;for (int i = 1; i <= len; i++) {temp[len - i] = ((a_len - i) >= 0 ? a.charAt(a_len - i) - '0' : 0) + ((b_len - i) >= 0 ? b.charAt(b_len - i) - '0' : 0) + tempInt;System.out.println("temp[len - i]: " + temp[len - i]);if (temp[len - i] > 1) {tempInt = 1;temp[len - i] = temp[len - i] - 2;} else {tempInt = 0;}}StringBuffer result = new StringBuffer();if (tempInt == 1) {result.append("1");}for (int i = 0; i < len; i++) {result.append(temp[i]);}return result.toString();}//https://leetcode.com/discuss/35278/short-ac-solution-in-java-with-explanation//优化public String addBinary1(String a, String b) {StringBuilder sb = new StringBuilder();int i = a.length() - 1, j = b.length() - 1, carry = 0;while (i >= 0 || j >= 0) {int sum = carry;if (j >= 0)sum += b.charAt(j--) - '0';if (i >= 0)sum += a.charAt(i--) - '0';sb.append(sum % 2);carry = sum / 2;}if (carry != 0)sb.append(carry);return sb.reverse().toString();}public static void main(String[] args) {String a = "1";String b = "101";System.out.println("addBinary: " + addBinary(a, b));}}
0 0
- LeetCode_67---Add Binary
- leetcode_67 add binary
- leetcode_67. Add Binary
- leetcode_67. Add Binary 字符串形式的二进制数相加
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- Add Binary
- 视频直播方面的知识ffmpeg
- C#判断用户是否使用微信浏览器,并据此来显示真实内容或二维码
- android 录制音频的时候,调用麦克风出停止
- 【Android】intent传递数据时,数据大小的限制问题
- windows笔记-虚拟内存
- LeetCode_67---Add Binary
- Google将不再支持Android Eclipse Tools
- Android旋转本地图片并保存
- js 支持兼容性的trim操作
- Android 为LinearLayout增加分割线 divider
- html 中文乱码
- ios构造函数
- C++关于二进制位操作小结
- xdebug安装和使用