Add Binary
程序员文章站
2022-06-04 10:58:35
...
题目表述
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"
分析:其实就是给定两个字符串,字符串中的值为二进制,让我们计算两个字符串中二进制相加,并返回结果。
我的Code如下:
class Solution {
public String addBinary(String a, String b) {
int maxLen = a.length();
if (b.length() > maxLen) {
maxLen = b.length();
}
// 把字符串a逆序存入数组A中
int[] arrayA = new int[a.length()];
for (int i = a.length() - 1; i >= 0; i--) {
arrayA[a.length() - 1 - i] = Integer.parseInt(a.charAt(i) + "");
}
int[] arrayB = new int[b.length()];
for (int i = b.length() - 1; i >= 0; i--) {
arrayB[b.length() - 1 - i] = Integer.parseInt(b.charAt(i) + "");
}
int[] array = new int[maxLen + 1];
if (a.length() > b.length()) {
for (int i = 0; i < arrayA.length; i++) {
if (i < b.length()) {
// 正常加
array[i] = arrayA[i] + arrayB[i] + array[i];
} else {
// b没了,就剩a
array[i] = arrayA[i] + array[i];
}
if (array[i] > 1) {
int chu = array[i] / 2;
int yu = array[i] % 2;
array[i] = yu;
array[i + 1] = chu;
}
}
} else {
for (int i = 0; i < arrayB.length; i++) {
if (i < a.length()) {
// 正常加
array[i] = arrayA[i] + arrayB[i] + array[i];
} else {
array[i] = arrayB[i] + array[i];
}
if (array[i] > 1) {
int chu = array[i] / 2;
int yu = array[i] % 2;
array[i] = yu;
array[i + 1] = chu;
}
}
}
// 倒序输出array即可
String str = "";
for (int i = array.length - 1; i >= 0; i--) {
if (i == array.length - 1) {
if (array[i] == 0) {
continue;
}
}
str += array[i] + "";
}
return str;
}
}
上一篇: Add Binary
下一篇: OAuth2.0详解(授权模式篇)
推荐阅读
-
关于mysql字符集设置了character_set_client=binary 在gbk情况下会出现表描述是乱码的情况
-
MySQL中的DATE_ADD应用场景_MySQL
-
javascript add event remove event_javascript技巧
-
二分查找(Binary Search)需要注意的问题,以及在数据库内核中的
-
jQuery.add() 函数的正确用法
-
力扣2. Add Two Numbers
-
ALTER TABLE ADD 增加多个字段 外键约束
-
MySQL:Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEM
-
完全掌握MySql之写入Binary Log的流程
-
WebService提供Add和getStudent服务(IIS发布)