码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] add-binary

时间:2018-09-23 13:38:32      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:static   https   sys   leetcode   知识点   example   center   www.   讲解   

时间限制:1秒 空间限制:32768K 热度指数:6434
本题知识点: 字符串 leetcode

 算法知识视频讲解

题目描述

 

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

For example,
a ="11"
b ="1"
Return"100".

 
题解:
 1 /*
 2 * 字符转化为整型: int a = ‘1‘ - ‘0‘;
 3 * 整型转化为字符: char a = String.valueOf(‘1‘).charAt(0);
 4 * */
 5 
 6 public class Solution {
 7     public String addBinary(String a, String b) {
 8         int lengthMax = Math.max(a.length(), b.length());
 9         StringBuilder sb = new StringBuilder();
10         int carry = 0;
11         int sum = 0;
12         for (int i = 0; i < lengthMax || carry != 0; i++) {
13             int an = 0, bn = 0;
14             if (a.length() - 1 - i >= 0) {
15                 an = a.charAt(a.length() - 1 - i) - ‘0‘;
16             }
17             if (b.length() - 1 - i >= 0) {
18                 bn = b.charAt(b.length() - 1 - i) - ‘0‘;
19             }
20             sum = an + bn + carry;
21             sb.append(sum % 2);
22             carry = sum / 2;
23         }
24         return sb.reverse().toString();
25     }
26 
27     public static void main(String args[]) {
28         Solution solution = new Solution();
29         String s = solution.addBinary("0", "0");
30         System.out.println("number: " + s.length());
31         System.out.println(s.charAt(0));
32     }
33 }

 

[leetcode] add-binary

标签:static   https   sys   leetcode   知识点   example   center   www.   讲解   

原文地址:https://www.cnblogs.com/yfzhou/p/9692164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!