[leetcode] add-binary
Posted yfzhou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] add-binary相关的知识,希望对你有一定的参考价值。
时间限制:1秒 空间限制:32768K 热度指数:6434
题目描述
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的主要内容,如果未能解决你的问题,请参考以下文章