当前位置:网站首页>LeetCode——Add Binary
LeetCode——Add Binary
2022-07-05 23:02:00 【全栈程序员站长】
大家好,又见面了,我是全栈君
Given two binary strings, return their sum (also a binary string).
For example, a = "11" b = "1"
Return "100".
求数字字符串的二进制和。
同之前的数组代表数字,两个数组相加一样。仅仅只是进位变成了2.可能两个串的长度不一样,故逆转。从左到右加下去。最后再逆转。
public static String addBinary(String a, String b) {
StringBuilder ar = new StringBuilder(a).reverse();
StringBuilder br = new StringBuilder(b).reverse();
StringBuilder result = new StringBuilder();
int len = Math.max(a.length(), b.length());
int carry = 0;//进位
for (int i = 0; i < len; i++) {
int t1 = (i >= a.length() ? 0 : (ar.charAt(i) - '0'));
int t2 = (i >= b.length() ? 0 : (br.charAt(i) - '0'));
int t3 = t1 + t2 + carry;
carry = t3 / 2;
t3 = t3 % 2;
result.append(t3);
}
if (carry != 0)
result.append(carry);
result.reverse();
return result.toString();
}版权声明:本文博客原创文章。博客,未经同意,不得转载。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/117531.html原文链接:https://javaforall.cn
边栏推荐
- Southeast Asia e-commerce guide, how do sellers layout the Southeast Asia market?
- d3dx9_ What if 29.dll is missing? System missing d3dx9_ Solution of 29.dll file
- UART Application Design and Simulation Verification 2 - TX Module Design (Stateless machine)
- Krypton Factor purple book chapter 7 violent solution
- 派对的最大快乐值
- [speech processing] speech signal denoising and denoising based on Matlab GUI low-pass filter [including Matlab source code 1708]
- Summary of binary tree recursive routines
- Go语言实现原理——锁实现原理
- LabVIEW打开PNG 图像正常而 Photoshop打开得到全黑的图像
- From the perspective of quantitative genetics, why do you get the bride price when you get married
猜你喜欢
随机推荐
14种神笔记方法,只需选择1招,让你的学习和工作效率提高100倍!
Hainan Nuanshen tea recruits warmhearted people: recruitment of the product experience recommender of Nuanshen multi bubble honey orchid single cluster
Development specification: interface unified return value format [resend]
The maximum happiness of the party
【Note17】PECI(Platform Environment Control Interface)
Global and Chinese markets of industrial pH meters 2022-2028: Research Report on technology, participants, trends, market size and share
判斷二叉樹是否為完全二叉樹
Use of grpc interceptor
3 find the greatest common divisor and the least common multiple
Object detection based on impulse neural network
Vision Transformer (ViT)
二叉树递归套路总结
Media query: importing resources
Shell: operator
VOT toolkit environment configuration and use
Global and Chinese markets of tantalum heat exchangers 2022-2028: Research Report on technology, participants, trends, market size and share
From the perspective of quantitative genetics, why do you get the bride price when you get married
基于脉冲神经网络的物体检测
查看网页最后修改时间方法以及原理简介
[untitled]









