当前位置:网站首页>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();
}
}
边栏推荐
猜你喜欢
SIP system composition format
[网鼎杯 2020 半决赛]AliceWebsite
Sql file import database - nanny level tutorial
[Numpy] np.where
第二十一周作业
[based] GO language. Why do I have to learn Golang and introduction to the language universal
Bika LIMS - SENAITE using open source LIMS set (users, roles and departments)
[WeChat applet] One article to solve button, input, image components
Navicat如何连接MySQL
如何把Netflix数据集转换成Movielens格式?
随机推荐
理解yolov7网络结构
C# autoCAD 几个经常用到的功能代码。
Legendary version adds npc modification, adds npc method and configuration parameter tutorial
[Numpy] np.where
第二十一周作业
拦截器与过滤器(三)@interface自定义注解拦截
Bika LIMS - SENAITE using open source LIMS set (users, roles and departments)
Nacos hierarchical storage model - the cluster configuration and NacosRule load balance
Mysql stored procedures, rounding
How Navicat Connects to MySQL
Nacos分级存储模型-集群配置与NacosRule负载均衡
IO流:节点流和处理流详细归纳。
conda环境创建及复制
Go简单实现协程池
【云原生】微服务之Feign的介绍与使用
TiCDC Migration - TiDB to MySQL Test
投资127亿!深圳,再添一所985
阿里云官方 Redis 开发规范!
「 工业缺陷检测深度学习方法」最新2022研究综述
MySql 5.7.38下载安装教程 ,并实现在Navicat操作MySql