Description

Given two binary strings, return their sum (also a binary string).

Example

a = 11

b = 1

Return 100

解题:二进制相加。我的思路是,先转成StringBuilder对象(reverse方法比较好用),因为相加是从最后开始,所以先用reverse方法倒转过来。和上一题类似,用carry变量表示进位,0为不进位,1为需要进一位。最后的结果再倒过来。具体细节标注在代码中,代码如下:

public class Solution {
/**
* @param a: a number
* @param b: a number
* @return: the result
*/
public String addBinary(String a, String b) {
// write your code here
StringBuilder sa = new StringBuilder(a);
StringBuilder sb = new StringBuilder(b);
StringBuilder res = new StringBuilder();
int carry = 0;//表示进位
sa.reverse();
sb.reverse();
int i = 0;
for(i = 0; i < sa.length() && i < sb.length(); i++){
int tpa = sa.charAt(i) - '0';
int tpb = sb.charAt(i) - '0';
if(carry == 0){ // 没有进位
if(tpa == 1 && tpb == 1){
carry = 1;
res.append('0');
}else{
char temp = (char)((int)'0' + (tpa+tpb));
res.append( temp );
}
}else{ //有进位;
if(tpa + tpb == 1){
carry = 1; // 依然有进位
res.append('0');
}else if( tpa + tpb == 2){
carry = 1;
res.append('1');
}else{
// 0 + 0
carry = 0;
res.append('1');
}
}
}
//对剩下的处理
while(i < sa.length()){
//把sa后面的接上去,但是要考虑进位
if(carry == 0){
res.append(sa.substring(i));
break;
}else{
//有进位
if(sa.charAt(i) == '1'){
res.append('0');
}else{
res.append('1');
carry = 0;
}
i++;
}
} while(i < sb.length()){
//把sa后面的接上去,但是要考虑进位
if(carry == 0){
res.append(sb.substring(i));
break;
}else{
//有进位
if(sb.charAt(i) == '1'){
res.append('0');
}else{
res.append('1');
carry = 0;
}
i++;
}
}
if(carry == 1)
res.append('1');
return res.reverse().toString();
}
}

408. Add Binary【LintCode java】的更多相关文章

  1. 365. Count 1 in Binary【LintCode java】

    Description Count how many 1 in binary representation of a 32-bit integer. Example Given 32, return  ...

  2. 376. Binary Tree Path Sum【LintCode java】

    Description Given a binary tree, find all paths that sum of the nodes in the path equals to a given ...

  3. 375. Clone Binary Tree【LintCode java】

    Description For the given binary tree, return a deep copy of it. Example Given a binary tree: 1 / \ ...

  4. 372. Delete Node in a Linked List【LintCode java】

    Description Implement an algorithm to delete a node in the middle of a singly linked list, given onl ...

  5. 245. Subtree【LintCode java】

    Description You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds ...

  6. 227. Mock Hanoi Tower by Stacks【LintCode java】

    Description In the classic problem of Towers of Hanoi, you have 3 towers and N disks of different si ...

  7. 451. Swap Nodes in Pairs【LintCode java】

    Description Given a linked list, swap every two adjacent nodes and return its head. Example Given 1- ...

  8. 445. Cosine Similarity【LintCode java】

    Description Cosine similarity is a measure of similarity between two vectors of an inner product spa ...

  9. 433. Number of Islands【LintCode java】

    Description Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. ...

随机推荐

  1. 安卓混合开发——原生Java和H5交互,保证你一看就懂!

    ** 在Android开发中,越来越多的商业项目使用了Android原生控件与WebView进行混合开发,当然不仅仅就是显示一个WebView那么简单,有时候还需要本地Java代码与HTML中的Jav ...

  2. 【Step By Step】将Dotnet Core部署到Docker上

    本教程的前提是,你已经在Linux服务器上已经成功的安装了Docker,我会大概介绍在此过程中用到的Docker命令,并不会介绍所有的Docker命令(因为我也不会). 一.在Docker中运行Dot ...

  3. Blocking Master Example QT 自带 的 serial 即 串口 例子

    1.官方解释文档:http://doc.qt.io/qt-5/qtserialport-blockingmaster-example.html Blocking Master shows how to ...

  4. IIS中ASP.NET虚拟目录不继承主站点web.config设置的办法(转载)

    ASP.NET提供了强大的Web.config来配置网站,一般来说一个网站只有一个根目录下的Web.config文件,有时候我们希望子目录有着不同的权限或者参数设置,则可以在相应子目录增加一个Web. ...

  5. 用JavaScript编写简单斗地主效果Es6

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. 07 consistent gets、db block gets的简单精辟的理解

    consistent gets.db block gets的简单精辟的理解     consistent gets:一致性读,为了保持读一致性而获取的块,其中可能包括undo block,也有包括非u ...

  7. es6解构赋值的几个用法

    1.解构赋值可以轻松获取对象或者数组中的数据 var jsonData = { data: "111", data2: ["test","test2& ...

  8. 初识ExtJS 6----自学笔记(一)

    一.使用环境 这一点写在前面,是为了方便大家在找资料的时候可以直接定位环境版本. ExtJS版本 6.2  中文官方网站提供版本,网站地址http://extjs.org.cn/node/793 开发 ...

  9. 分布式日志收集框架Flume

    分布式日志收集框架Flume 1.业务现状分析 WebServer/ApplicationServer分散在各个机器上 想在大数据平台Hadoop进行统计分析 日志如何收集到Hadoop平台上 解决方 ...

  10. 20190305-leetcode题目有效的括号

    给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭合. 左括号必须以正确的顺序闭合. 注意空字符串可被认 ...