| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.NumberOfStepsToReduceNumberInBinaryRepresentationToOne; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class NumberOfStepsToReduceNumberInBinaryRepresentationToOneGreedy : |
| | | 16 | | INumberOfStepsToReduceNumberInBinaryRepresentationToOne |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// Time complexity - O(n) |
| | | 20 | | /// Space complexity - O(1) |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="s"></param> |
| | | 23 | | /// <returns></returns> |
| | | 24 | | public int NumSteps(string s) |
| | 4 | 25 | | { |
| | 4 | 26 | | var steps = 0; |
| | | 27 | | |
| | 4 | 28 | | var carry = 0; |
| | | 29 | | |
| | 130 | 30 | | for (var i = s.Length - 1; i > 0; i--) |
| | 61 | 31 | | { |
| | 61 | 32 | | if ((s[i] - '0' + carry) % 2 == 0) |
| | 32 | 33 | | { |
| | 32 | 34 | | steps++; |
| | 32 | 35 | | } |
| | | 36 | | else |
| | 29 | 37 | | { |
| | 29 | 38 | | steps += 2; |
| | | 39 | | |
| | 29 | 40 | | carry = 1; |
| | 29 | 41 | | } |
| | 61 | 42 | | } |
| | | 43 | | |
| | 4 | 44 | | return steps + carry; |
| | 4 | 45 | | } |
| | | 46 | | } |