简体   繁体   中英

My program is too long. I want to shorten it using a loop method

I am trying to find a lucky number from my birthday, ex: 1985 June 07. My birthday lucky number 1+9+8+5+6+7=36 >> 3+6 = 9. My lucky number is 9. I tried to code. I used while code 4 times. I want to shorten it and I want to get the digit sum of any length number. How to code it?

c#

private void btn_lucky_Click(object sender, EventArgs e)
        {
            string Bday = dateTimePicker1.Text.Replace("-", "");


        int Bnumber = int.Parse(Bday);



        int a1 = Bnumber, sum1 = 0, b1;


        while (a1 != 0)
        {
            b1 = a1 % 10;
            sum1 = sum1 + b1;
            a1 = a1 / 10;
        }


        txt_lucky.Text = sum1.ToString();

        if (sum1 < 10)
        {
            txt_lucky.Text = sum1.ToString();
        }

        int a2 = sum1, sum2 = 0, b2;

        if (sum1 > 9)
        {
            while (a2 != 0)
            {
                b2 = a2 % 10;
                sum2 = sum2 + b2;
                a2 = a2 / 10;
            }
            txt_lucky.Text = sum2.ToString();
        }

        int a3 = sum2, sum3 = 0, b3;
        if (sum2 > 9)
        {
            while (a3 != 0)
            {
                b3 = a3 % 10;
                sum3 = sum3 + b3;
                a3 = a3 / 10;
            }
            txt_lucky.Text = sum3.ToString();
        }


    }

This is a great candidate for recursion, which you can do if you make a function that returns the same type of output as its input. It will repeat itself until it ends up with a one-digit number.

public static string LuckyNumber(string date) // "06/07/1985"
{
  var result = (date ?? "")       // in case date is null
    .ToCharArray()                // ['0','6','/','0','7','/','1','9','8','5']
    .Where(char.IsNumber)         // ['0','6','0','7','1','9','8','5']
    .Select(char.GetNumericValue) // [0,6,0,7,1,9,8,5]
    .Sum()                        //  36
    .ToString();                  // "36"

  if (result.Length == 1) return result; //"36" is not 1 digit, so...
  return LuckyNumber(result);            //repeat the above with "36"
}

Implementation:

string date = "06/07/1985";
var luckyNumber = LuckyNumber(date);
System.Console.WriteLine(luckyNumber);

fiddle: https://dotnetfiddle.net/5M7Ozv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM