Is there any better way to find the digit multiplication and summation?

前端 未结 1 1570
情话喂你
情话喂你 2021-01-24 01:12
int N = 2345;
        var digitArray = N.ToString().ToCharArray();
        int multiplicationSum = 1;
        foreach (char digit in digitArray)
        {
            mu         


        
相关标签:
1条回答
  • 2021-01-24 01:31

    Assuming you don't need to deal with negative numbers, it seems doing it mathematically would make a lot more sense

    int N = 2345;
    int multiplicationSum = 1;
    while(N!=0)
    {
      multiplicationSum = multiplicationSum * (N%10);
      N = N/10;
    }
    var sum = 0;
    while(multiplicationSum!=0)
    {
      sum = sum + (multiplicationSum%10);
      multiplicationSum = multiplicationSum/10;
    }
    

    References:

    % operator

    The % operator computes the remainder after dividing its first operand by its second

    / operator:

    When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2

    0 讨论(0)
提交回复
热议问题