赞
踩
题目来源:LeetCode 67. 二进制求和
//Java:二进制加法 public class JFETK5 { public static void main(String[] args) { Solution solution = new JFETK5().new Solution(); // TO TEST System.out.println(solution.addBinary("101111","10")); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public String addBinary(String a, String b) { // 1.逆序字符串 StringBuilder sa = new StringBuilder(); StringBuilder sb = new StringBuilder(); sa.append(a); sb.append(b); sa.reverse(); sb.reverse(); // 2.长度短的那个字符串补零 int n = 0; if(sa.length() > sb.length()) { n = sa.length() - sb.length(); for(int i = 0 ; i < n ; i++) { sb.append('0'); } } else if (sa.length() < sb.length()){ n = sb.length() - sa.length(); for(int i = 0 ; i < n ; i++) { sa.append('0'); } } // 3.逐位进行加法运算 StringBuilder stringBuilder = new StringBuilder(); int flag = 0; // 判断是否有进位,有进位则为1,否则为0,不用boolean是为方便计算 for(int i = 0 ; i < sa.length() && i < sb.length() ; i++) { if(flag == 0) { // 没有进位 if(sa.charAt(i) == sb.charAt(i) && sa.charAt(i) == '0') { flag = 0; stringBuilder.append('0'); } else if(sa.charAt(i) == sb.charAt(i) && sa.charAt(i) == '1') { flag = 1; stringBuilder.append('0'); } else { flag = 0; stringBuilder.append('1'); } } else if(flag == 1){ // 有进位 if(sa.charAt(i) == sb.charAt(i) && sa.charAt(i) == '0') { flag = 0; stringBuilder.append('1'); } else if(sa.charAt(i) == sb.charAt(i) && sa.charAt(i) == '1') { flag = 1; stringBuilder.append('1'); } else { flag = 1; stringBuilder.append('0'); } } } if(flag == 1) { stringBuilder.append('1'); } // 逆序stringBuilder return stringBuilder.reverse().toString(); } } //leetcode submit region end(Prohibit modification and deletion) }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。