当前位置:网站首页>Leetcode67. 二进制求和
Leetcode67. 二进制求和
2022-07-29 12:52:00 【Java全栈研发大联盟】
题目传送地址: https://leetcode.cn/problems/add-binary/
运行效率
代码如下:
class Solution {
public static String addBinary(String a, String b) {
StringBuilder res = new StringBuilder();
int left = a.length() - 1;
int right = b.length() - 1;
int carry = 0;// 进位
while ((left >= 0 && right >= 0) || carry == 1) {
int i = 0;
if (left >= 0) {
i = a.charAt(left) - '0';
}
int i1 = 0;
if (right >= 0) {
i1 = b.charAt(right) - '0';
}
int sum = i + i1 + carry;
if (sum >= 2) {
carry = 1;
} else {
carry = 0;
}
res.insert(0, sum % 2);
left--;
right--;
}
if (left >= 0) {
String substring = a.substring(0, left + 1);
res.insert(0, substring);
}
if (right >= 0) {
String substring = b.substring(0, right + 1);
res.insert(0, substring);
}
return res.toString();
}
}
边栏推荐
猜你喜欢

Go-Excelize API源码阅读(七)—— CopySheet(from, to int)

2022 IDEA (学生邮箱认证)安装使用教程以及基础配置教程
![[WeChat applet] WXSS and global, page configuration](/img/ff/fe4c827bc887b8afefa72dc9b230af.jpg)
[WeChat applet] WXSS and global, page configuration

TiDB upgrade share with case (TiDB v4.0.1 to v5.4.1)

The whole process of installing Oracle database on CentOS7

Container is changed | deploy MySQL cluster in the Rancher

String.split()最详细源码解读及注意事项

SIP系统组成格式

C语言小游戏------贪吃蛇----小白专用

xxl-job源码解析(技术分享)
随机推荐
Nacos hierarchical storage model - the cluster configuration and NacosRule load balance
网页被劫持跳转怎么办?发布网修复方法
【MySQL视图】视图的概念、创建、查看、删除和修改
图解 Attention(完整版)!
【微信小程序】一文解决button、input、image组件
Bika LIMS 开源LIMS集—— SENAITE的使用(用户、角色、部门)
常坐飞机的你,为什么老惦记着“升舱”?
The whole process of installing Oracle database on CentOS7
DVWA full level customs clearance tutorial
DVWA全级别通关教程
【kaggle】Spaceship Titanic - 预测哪些乘客被运送到另一个维度【CatBoost - 10%】
JS_ deleting the invalid data in the array undefined '0' null false NaN
「 工业缺陷检测深度学习方法」最新2022研究综述
基于对象的实时空间音频渲染丨Dev for Dev 专栏
[WeChat applet] WXSS and global, page configuration
投资127亿!深圳,再添一所985
Nacos分级存储模型-集群配置与NacosRule负载均衡
38.【string下章】
[GO语言基础] 一.为什么我要学习Golang以及GO语言入门普及
RedisTemplate使用详解