leetcode67
Posted AsenYang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode(剑指 Offer)- 67. 把字符串转换成整数