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为需要进一位。最后的结果再倒过来。具体细节标注在代码中,代码如下:

  1. public class Solution {
  2. /**
  3. * @param a: a number
  4. * @param b: a number
  5. * @return: the result
  6. */
  7. public String addBinary(String a, String b) {
  8. // write your code here
  9. StringBuilder sa = new StringBuilder(a);
  10. StringBuilder sb = new StringBuilder(b);
  11. StringBuilder res = new StringBuilder();
  12. int carry = 0;//表示进位
  13. sa.reverse();
  14. sb.reverse();
  15. int i = 0;
  16. for(i = 0; i < sa.length() && i < sb.length(); i++){
  17. int tpa = sa.charAt(i) - '0';
  18. int tpb = sb.charAt(i) - '0';
  19. if(carry == 0){ // 没有进位
  20. if(tpa == 1 && tpb == 1){
  21. carry = 1;
  22. res.append('0');
  23. }else{
  24. char temp = (char)((int)'0' + (tpa+tpb));
  25. res.append( temp );
  26. }
  27. }else{ //有进位;
  28. if(tpa + tpb == 1){
  29. carry = 1; // 依然有进位
  30. res.append('0');
  31. }else if( tpa + tpb == 2){
  32. carry = 1;
  33. res.append('1');
  34. }else{
  35. // 0 + 0
  36. carry = 0;
  37. res.append('1');
  38. }
  39. }
  40. }
  41. //对剩下的处理
  42. while(i < sa.length()){
  43. //把sa后面的接上去,但是要考虑进位
  44. if(carry == 0){
  45. res.append(sa.substring(i));
  46. break;
  47. }else{
  48. //有进位
  49. if(sa.charAt(i) == '1'){
  50. res.append('0');
  51. }else{
  52. res.append('1');
  53. carry = 0;
  54. }
  55. i++;
  56. }
  57. }
  58.  
  59. while(i < sb.length()){
  60. //把sa后面的接上去,但是要考虑进位
  61. if(carry == 0){
  62. res.append(sb.substring(i));
  63. break;
  64. }else{
  65. //有进位
  66. if(sb.charAt(i) == '1'){
  67. res.append('0');
  68. }else{
  69. res.append('1');
  70. carry = 0;
  71. }
  72. i++;
  73. }
  74. }
  75. if(carry == 1)
  76. res.append('1');
  77. return res.reverse().toString();
  78. }
  79. }

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. ListView 中的TextView实现跑马灯效果

    案例:怎么样在一个ListView中含有TextView的item中实现字母滚动呢.这个在一些特定的场合经常用得到.如下图,当焦点位于某个item的时候其内容就自动滚动显示 要实现这样的效果,废话不多 ...

  2. 使用 JLINK 的 RTT 功能 进行 调试打印数据

    jlink V9 时,在 SWD 接口 模式 时  ,要 接 SWO 这个引脚 ,否则导致 在 FreeRTOS的任务中不能使用,  正确的 接线方法 是  VCC,GND,SWDIO,SWCLK,S ...

  3. STM32启动代码分析

    STM32启动文件简单分析(STM32F10x.s适用范围)定时器, 型号, 名字在<<STM32不完全手册里面>>,我们所有的例程都采用了一个叫STM32F10x.s的启动文 ...

  4. stm32 晶振不起振

    1. STM32f103有内部晶振.刚刚上电时,所有Clock都是源于内部晶振,所以当片内没有程序或内部程序没有使能外部晶振时,外部晶振是不会起振的.2. STM32f103有内部复位电路,只有当检测 ...

  5. 在CentOS上安装node.js的时候报错:No acceptable C compiler found!解决办法

    在CentOS上安装node.js的时候报错:No acceptable C compiler found! 原因:没有c编译器. 解决办法:安装GCC 命令如下: #yum install gcc ...

  6. CSP 试题编号201803-2 Java实现

    package HB; import java.util.Scanner; public class Test_06 { public static void main(String[] args) ...

  7. 复习宝典之Mysql数据库

    查看更多宝典,请点击<金三银四,你的专属面试宝典> 第一章:mysql数据库 1)mysql与mariaDb MariaDB数据库管理系统是MySQL的一个分支,主要由开源社区在维护,采用 ...

  8. activemq的高级特性:消息持久订阅

    activemq的高级特性之消息持久订阅 如果采用topic模式发送的时候,mq关闭了或消费者关闭了.在启动的时候,就会收不到mq发送的消息,所以就会出现消息持久订阅. 消息持久订阅:第一:消息要持久 ...

  9. CentOS7.6离线安装Redis5.0.4

    安装gcc-c++: 检查是否存在gcc-c++:rpm -qa|grep gcc-c++ 如果不存在就下载Linux-GC-C++文件: 访问镜像网站:http://mirrors.aliyun.c ...

  10. 用js实现导出功能将html中的table导出为excel

    /** * 描述:导出表格对应的excel文件 * 时间:2018-03-29 * 作者:任恩远 * 调用示例: * onclick = "tableToExcel(tableId,file ...