标签:static https sys leetcode 知识点 example center www. 讲解
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 }
标签:static https sys leetcode 知识点 example center www. 讲解
原文地址:https://www.cnblogs.com/yfzhou/p/9692164.html