Sum of digits in C#

前端 未结 18 2070
耶瑟儿~
耶瑟儿~ 2020-11-28 07:21

What\'s the fastest and easiest to read implementation of calculating the sum of digits?

I.e. Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21

18条回答
  •  长情又很酷
    2020-11-28 07:43

    If one wants to perform specific operations like add odd numbers/even numbers only, add numbers with odd index/even index only, then following code suits best. In this example, I have added odd numbers from the input number.

    using System;
                        
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("Please Input number");
            Console.WriteLine(GetSum(Console.ReadLine()));
        }
        
        public static int GetSum(string num){
            int summ = 0;
            for(int i=0; i < num.Length; i++){
                int currentNum;
                if(int.TryParse(num[i].ToString(),out currentNum)){
                     if(currentNum % 2 == 1){
                        summ += currentNum;
                    }
                }
           } 
           return summ;
        }
    }
    

提交回复
热议问题