Add Binary
程序员文章站
2022-06-04 10:58:41
...
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
我的解法:
把字符串拆开,从后往前进行二进制加法运算。注意两点:1、边界条件判断,什么时候需要取0(一长一短的时候)。2、string.charAt要小心取值,避免数据越界。
class Solution {
public String addBinary(String a, String b) {
//先统计a,b长度
//判断哪个长,取长的作为结果字符串的长度
int al = a.length();
int bl = b.length();
int n = Math.max(al,bl);
StringBuffer res = new StringBuffer();
int carry = 0;
int tempa = 0;
int tempb = 0;
for(int i = 0; i<n; i++){
tempa = al>i ? a.charAt(al-i-1)-'0' : 0;
tempb = bl>i ? b.charAt(bl-i-1)-'0' : 0;
res.insert(0,(tempa+tempb+carry)%2);
carry = (tempa+tempb+carry)>1? 1 : 0;
}
if(carry == 1) res.insert(0,1);
return res.toString();
}
}
上一篇: Dynamic Create COM Attribute
下一篇: Add Binary
推荐阅读
-
jquery中.add()的使用方法解析
-
IDEA中add framework support时缺少Spring,Java EE等框架支持
-
报错android.view.InflateException: Binary XML file line #11: Attempt to invoke vir
-
在Parallel中使用DbSet.Add()发现的一系列多线程问题和解决思路详解
-
Binary XML file line #19: <item> tag requires a ‘drawable‘ attribute or child tag defining a drawabl
-
The BINARY and VARBINARY data types_MySQL
-
How to Add a Shortcode in WordPress? (Beginner’s Guide
-
How to add OpenCV library in spring web application
-
完全掌握MySql之写入Binary Log的流程
-
How to Add the JVM Component to an Existing Oracle Database