首页 > 代码库 > leetcode67
leetcode67
public class Solution { public string AddBinary(string a, string b) { var list = new List<string>(); if (a.Length > b.Length) { //补充b的长度 var dif = a.Length - b.Length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < dif; i++) { sb.Append("0"); } b = sb.ToString() + b; var len = a.Length; var jin = 0; for (int i = len - 1; i >= 0; i--) { var ca = Convert.ToInt32(a[i].ToString()); var cb = Convert.ToInt32(b[i].ToString()); var cur = ca + cb + jin; if (cur >= 2) { jin = 1; } else { jin = 0; } cur = cur % 2; list.Add(cur.ToString()); } if (jin == 1) { list.Add("1"); } } else { var dif = b.Length - a.Length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < dif; i++) { sb.Append("0"); } a = sb.ToString() + a; var len = b.Length; var jin = 0; for (int i = len - 1; i >= 0; i--) { var ca = Convert.ToInt32(a[i].ToString()); var cb = Convert.ToInt32(b[i].ToString()); var cur = ca + cb + jin; if (cur >= 2) { jin = 1; } else { jin = 0; } cur = cur % 2; list.Add(cur.ToString()); } if (jin == 1) { list.Add("1"); } } StringBuilder sbx = new StringBuilder(); for (int i = list.Count - 1; i >= 0; i--) { sbx.Append(list[i]); } return sbx.ToString(); } }
https://leetcode.com/problems/add-binary/#/description
leetcode67
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。