Home > other >  Recursively summing start and end digits of a number until only two are left
Recursively summing start and end digits of a number until only two are left

Time:02-23

What I am trying to implement is the following: Let's say we have a number (in string format) "34322". I want to sum the start and end digits, then keep repeating this process on the leftover digits until only two digits are left. In other words:

3 2=5, 4 2=6, 3 (563)
5 3=8, 6 (86)

I have the following method:

string ShortenNumber(string num)
{
    int firstDigit = int.Parse(num.Substring(0, 1));
    int lastDigit = int.Parse(num.Substring(num.Length - 1, 1));
    
    if (num.Length <= 2)
    {
        return num;
    }

    return (firstDigit   lastDigit).ToString()   ShortenNumber(num.Substring(1, num.Length - 2));
}

The above gives the result 563, but stops there. How can I achieve the desired behaviour?

CodePudding user response:

Use recursion on the whole number (34322 or 563), and not on the partial number (432 for instance, when you take out starting 3 and ending 2). So, the function should somehow (you have to code it) calculate output 563 from input 34322, and ONLY THEN use that output 563 as input to the recursive call.

You calculate 563 from 34322 using a loop.

Pay attention, from your answer to my question in comments, there should exist one "% 10" in the code.

CodePudding user response:

You can use this approach:

public static string ShortenNumber(string num)
{
    num = num?.Trim();
    if (string.IsNullOrEmpty(num) || num.Length == 1 || !int.TryParse(num, out _)) 
        return num;
    StringBuilder sb = new StringBuilder();
    int endIndex = num.Length / 2;
    Func<char, int> charToInt = c => c - '0';
    for (int i = 0; i < endIndex; i  )
    {
        sb.Append(charToInt(num[i])   charToInt(num[num.Length - i - 1]));
    }
    if(num.Length % 2 == 1) 
        sb.Append(charToInt(num[endIndex])); // take middle part last
    return sb.ToString();
}    

string input = "34322";
string result = input;
while ((result = ShortenNumber(result)).Length > 2) // infinite loop possible
    ShortenNumber(result);
  • Related