| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.AddBinary; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class AddBinaryLinear : IAddBinary |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(max(n, m)), where n is the length of string a and is the length of string b |
| | 19 | | /// Space complexity - O(max(n, m)), where n is the length of string a and is the length of string b |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="a"></param> |
| | 22 | | /// <param name="b"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public string AddBinary(string a, string b) |
| 3 | 25 | | { |
| 3 | 26 | | var result = new char[Math.Max(a.Length, b.Length) + 1]; |
| | 27 | |
|
| 3 | 28 | | var aIndex = a.Length - 1; |
| 3 | 29 | | var bIndex = b.Length - 1; |
| 3 | 30 | | var resultIndex = result.Length - 1; |
| | 31 | |
|
| 3 | 32 | | var carry = 0; |
| | 33 | |
|
| 12 | 34 | | while (aIndex >= 0 || bIndex >= 0) |
| 9 | 35 | | { |
| 9 | 36 | | var sum = carry; |
| | 37 | |
|
| 9 | 38 | | if (aIndex >= 0) |
| 9 | 39 | | { |
| 9 | 40 | | sum += (int)char.GetNumericValue(a[aIndex]); |
| 9 | 41 | | aIndex--; |
| 9 | 42 | | } |
| | 43 | |
|
| 9 | 44 | | if (bIndex >= 0) |
| 7 | 45 | | { |
| 7 | 46 | | sum += (int)char.GetNumericValue(b[bIndex]); |
| 7 | 47 | | bIndex--; |
| 7 | 48 | | } |
| | 49 | |
|
| 9 | 50 | | carry = sum / 2; |
| 9 | 51 | | result[resultIndex--] = (char)((sum % 2) + '0'); |
| 9 | 52 | | } |
| | 53 | |
|
| 3 | 54 | | if (carry <= 0) |
| 0 | 55 | | { |
| 0 | 56 | | return new string(result, resultIndex + 1, result.Length - resultIndex - 1); |
| | 57 | | } |
| | 58 | |
|
| 3 | 59 | | result[resultIndex] = (char)(carry + '0'); |
| | 60 | |
|
| 3 | 61 | | return new string(result).TrimStart('0'); |
| 3 | 62 | | } |
| | 63 | | } |