简体   繁体   English

C#中的数字总和

[英]Sum of digits in C#

What's the fastest and easiest to read implementation of calculating the sum of digits?计算数字总和的最快和最容易阅读的实现是什么?

Ie Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21即给定数字:17463 = 1 + 7 + 4 + 6 + 3 = 21

You could do it arithmetically, without using a string:您可以在不使用字符串的情况下进行算术运算:

sum = 0;
while (n != 0) {
    sum += n % 10;
    n /= 10;
}

I use我用

int result = 17463.ToString().Sum(c => c - '0');

It uses only 1 line of code.它仅使用 1 行代码。

For integer numbers, Greg Hewgill has most of the answer, but forgets to account for the n < 0. The sum of the digits of -1234 should still be 10, not -10.对于整数,Greg Hewgill 有大部分答案,但忘记考虑 n < 0。-1234 的数字总和应该仍然是 10,而不是 -10。

n = Math.Abs(n);
sum = 0;
while (n != 0) {
    sum += n % 10;
    n /= 10;
}

It the number is a floating point number, a different approach should be taken, and chaowman's solution will completely fail when it hits the decimal point.如果数字是浮点数,则应采取不同的方法,而chaowman的解决方案在达到小数点时将完全失败。

int num = 12346;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;
 public static int SumDigits(int value)
 {
     int sum = 0;
     while (value != 0)
     {
         int rem;
         value = Math.DivRem(value, 10, out rem);
         sum += rem;
     }
     return sum;
 }

I thought I'd just post this for completion's sake:我以为我只是为了完成而发布这个:

If you need a recursive sum of digits, eg: 17463 -> 1 + 7 + 4 + 6 + 3 = 21 -> 2 + 1 = 3如果您需要递归数字总和,例如: 17463 -> 1 + 7 + 4 + 6 + 3 = 21 -> 2 + 1 = 3
then the best solution would be那么最好的解决方案是

int result = input % 9;
return (result == 0 && input > 0) ? 9 : result;

I like the chaowman's response, but would do one change我喜欢 chaowman 的回应,但会做一个改变

int result = 17463.ToString().Sum(c => Convert.ToInt32(c));

I'm not even sure the c - '0', syntax would work?我什至不确定 c - '0',语法是否有效? (substracting two characters should give a character as a result I think?) (我认为减去两个字符应该得到一个字符?)

I think it's the most readable version (using of the word sum in combination with the lambda expression showing that you'll do it for every char).我认为这是最易读的版本(将单词 sum 与 lambda 表达式结合使用,表明您将对每个字符执行此操作)。 But indeed, I don't think it will be the fastest.但事实上,我认为它不会是最快的。

int n = 17463; int sum = 0;
for (int i = n; i > 0; i = i / 10)
{
sum = sum + i % 10;
}
Console.WriteLine(sum);
Console.ReadLine();
private static int getDigitSum(int ds)
{
    int dssum = 0;            
    while (ds > 0)
    {
        dssum += ds % 10;
        ds /= 10;
        if (dssum > 9)
        {                
            dssum -= 9;
        }
    }
    return dssum;
}

This is to provide the sum of digits between 0-9这是提供0-9之间的数字总和

I would suggest that the easiest to read implementation would be something like:我建议最容易阅读的实现是这样的:

public int sum(int number)
{
    int ret = 0;
    foreach (char c in Math.Abs(number).ToString())
        ret += c - '0';
    return ret;
}

This works, and is quite easy to read.这是有效的,并且很容易阅读。 BTW: Convert.ToInt32('3') gives 51, not 3. Convert.ToInt32('3' - '0') gives 3.顺便说一句:Convert.ToInt32('3') 给出 51,而不是 3。 Convert.ToInt32('3' - '0') 给出 3。

I would assume that the fastest implementation is Greg Hewgill's arithmetric solution.我认为最快的实现是 Greg Hewgill 的算术解决方案。

int j, k = 1234;
for(j=0;j+=k%10,k/=10;);
while(ino!=0 )
{
  digit=(ino%10));
  printf("%d",digit);
  ino=ino/10;   
}           

for an array like this i/p:10 25 712 65 对于像这样的阵列i / p:10 25 712 65

this wont work you have to try other logic if someone got one please post it for addition of array elements. 这不会工作你必须尝试其他逻辑如果有人有一个请发布它添加数组元素。

A while back, I had to find the digit sum of something.不久前,我必须找到某物的数字总和。 I used Muhammad Hasan Khan's code, however it kept returning the right number as a recurring decimal, ie when the digit sum was 4, i'd get 4.44444444444444 etc. Hence I edited it, getting the digit sum correct each time with this code:我使用了 Muhammad Hasan Khan 的代码,但是它一直返回正确的数字作为循环小数,即当数字总和为 4 时,我会得到 4.444444444444444 等。因此我对其进行了编辑,每次使用以下代码都使数字总和正确:

 double a, n, sumD;
 for (n = a; n > 0; sumD += n % 10, n /= 10);
 int sumI = (int)Math.Floor(sumD);

where a is the number whose digit sum you want, n is a double used for this process, sumD is the digit sum in double and sumI is the digit sum in integer, so the correct digit sum.其中 a 是您想要的数字总和的数字,n 是用于此过程的双精度数,sumD 是双精度数的数字总和,而 sumI 是整数的数字总和,因此是正确的数字总和。

static int SumOfDigits(int num)
{
    string stringNum = num.ToString();
    int sum = 0;
    for (int i = 0; i < stringNum.Length; i++)
    {
      sum+= int.Parse(Convert.ToString(stringNum[i]));

    }
    return sum;
}

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;
    }
}
public static int SumDigits1(int n)
{
    int sum = 0;
    int rem;
    while (n != 0)
    {           
        n = Math.DivRem(n, 10, out rem);
        sum += rem;
    }
    return sum;
}

public static int SumDigits2(int n)
{
    int sum = 0;
    int rem;
    for (sum = 0; n != 0; sum += rem)   
        n = Math.DivRem(n, 10, out rem);        
    return sum;
}   

public static int SumDigits3(int n)
{
    int sum = 0;    
    while (n != 0)
    {
        sum += n % 10;
        n /= 10;
    }   
    return sum;
}   

Complete code in: https://dotnetfiddle.net/lwKHyA完整代码: https : //dotnetfiddle.net/lwKHyA

The simplest and easiest way would be using loops to find sum of digits .最简单和最简单的方法是使用循环来查找数字总和

int sum = 0;
int n = 1234;

while(n > 0)
{
    sum += n%10;
    n /= 10;
}
#include <stdio.h>

int main (void) {

    int sum = 0;
    int n;
    printf("Enter ir num ");
    scanf("%i", &n);

    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }

    printf("Sum of digits is %i\n", sum);

    return 0;
}

Surprised nobody considered the Substring method.令人惊讶的是没有人考虑过 Substring 方法。 Don't know whether its more efficient or not.不知道它是否更有效。 For anyone who knows how to use this method, its quite intuitive for cases like this.对于任何知道如何使用这种方法的人来说,对于这样的情况,它非常直观。

string number = "17463";
int sum = 0;
String singleDigit = "";
for (int i = 0; i < number.Length; i++)
{
singleDigit = number.Substring(i, 1);
sum = sum + int.Parse(singleDigit);
}
Console.WriteLine(sum);
Console.ReadLine();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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