博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 67. Add Binary【个位补0,不必对齐】【easy】
阅读量:4363 次
发布时间:2019-06-07

本文共 782 字,大约阅读时间需要 2 分钟。

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"

class Solution {    public String addBinary(String a, String b) {        StringBuilder sb = new StringBuilder();        int i = a.length()-1, j = b.length()-1, carry = 0;        while(i >= 0 || j >= 0){            int sum = carry;            if(i >= 0) sum += a.charAt(i--) - '0';            if(j >= 0) sum += b.charAt(j--) - '0';            sb.append(sum % 2);            carry = sum / 2;        }        if(carry != 0) sb.append(carry);        return sb.reverse().toString();    }}

转载于:https://www.cnblogs.com/Roni-i/p/11184420.html

你可能感兴趣的文章
作业三
查看>>
动态生成Excel到客户端
查看>>
计蒜客 蒜头君的兔子
查看>>
七步从AngularJS菜鸟到专家(4和5):指令和表达式
查看>>
java httpclient post xml demo
查看>>
Git commit 提交信息有误,撤消 操作
查看>>
最长上升子序列的二分优化
查看>>
Struts2中一个action调用多个方法以及动态方法的调用
查看>>
调用webservice
查看>>
node 爬虫(-)
查看>>
Unity部署的EXE文件双击后没有任何反应(Crash)--Q盾这个坑!
查看>>
线程,进程,IO多路复用,协程的代码
查看>>
集线器(HUB)、交换机、路由器的区别和联系 及OSI七层模型 及TCP/IP通信协议...
查看>>
7.29多态
查看>>
spring入门之环境搭建
查看>>
ORM中一个很重要的方法BuildConditionSetSql
查看>>
Youth -Samuel Ullman
查看>>
day06_方法_20150806
查看>>
wamp安装后打开默认网页显示dir,图标红点
查看>>
javascript参考手册CHM中文版,以及PHP,MYSQL,DHTML参考手册下载
查看>>