1903. Largest Odd Number in String (LeetCode) (solution: C++, C#)

  

Problem Name: 1903. Largest Odd Number in String
Problem Link: https://leetcode.com/problems/largest-odd-number-in-string/
Difficulty: Easy
Tag: Math | String | Greedy,
Language: C# | C++
OJ: LeetCode

Algorithm:
1.Initialize an empty string answer and a variable position to -1.
2.Iterate through the input string num from right to left.
Find the rightmost odd digit and store its position in the variable position.
Break out of the loop once the rightmost odd digit is found.
3.Check if the rightmost odd digit is already at the end of the string.
If true, set answer to the original string num.
If false, set answer to the substring of num from the beginning to the position of the rightmost odd digit.
4.Return the final value of answer.

Code(C#)
public class Solution
{
    public string LargestOddNumber(string num)
    {
        string answer = "";
        int position = -1;
        for (int i = num.Length-1; i >= 0; i--)
            if ((int)(num[i]-'0') % 2 == 1)
            {
                position = i;
                break;
            }
        if (position == num.Length-1) answer = num;
        else answer = num.Remove(position + 1);
        return answer;
    }
}

Code(C++)
class Solution {
public:
    string largestOddNumber(string num) {
        ///Upcoming
    }
};