📜  程序给定数字的总和

📅  最后修改于: 2021-05-30 02:55:52             🧑  作者: Mango

给定一个数字,找到其数字的总和。

例子 :

Input : n = 687
Output : 21

Input : n = 12
Output : 3

给定数字中数字总和的通用算法:

  1. 取得号码
  2. 声明一个变量以存储总和并将其设置为0
  3. 重复接下来的两个步骤,直到数字不为0
  4. 借助余数’%’运算符,将其除以10,然后将其加到总和中,即可得到数字的最右边数字。
  5. 借助“ /”运算符将数字除以10,以删除最右边的数字。
  6. 打印或返回总和

以下是获得数字总和的解决方案。
1.迭代:

C++
// C program to compute sum of digits in
// number.
#include 
using namespace std;
 
/* Function to get sum of digits */
class gfg {
public:
    int getSum(int n)
    {
        int sum = 0;
        while (n != 0) {
            sum = sum + n % 10;
            n = n / 10;
        }
        return sum;
    }
};
 
// Driver code
int main()
{
    gfg g;
    int n = 687;
    cout << g.getSum(n);
    return 0;
}
// This code is contributed by Soumik


C
// C program to compute sum of digits in
// number.
#include 
 
/* Function to get sum of digits */
int getSum(int n)
{
    int sum = 0;
    while (n != 0) {
        sum = sum + n % 10;
        n = n / 10;
    }
    return sum;
}
 
// Driver code
int main()
{
    int n = 687;
    printf(" %d ", getSum(n));
    return 0;
}


Java
// Java program to compute
// sum of digits in number.
import java.io.*;
 
class GFG {
 
    /* Function to get sum of digits */
    static int getSum(int n)
    {
        int sum = 0;
 
        while (n != 0) {
            sum = sum + n % 10;
            n = n / 10;
        }
 
        return sum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 687;
 
        System.out.println(getSum(n));
    }
}
 
// This code is contributed by Gitanjali


Python3
# Python 3 program to
# compute sum of digits in
# number.
 
# Function to get sum of digits
 
 
def getSum(n):
 
    sum = 0
    while (n != 0):
 
        sum = sum + int(n % 10)
        n = int(n/10)
 
    return sum
 
 
# Driver code
n = 687
print(getSum(n))


C#
// C# program to compute
// sum of digits in number.
using System;
 
class GFG {
    /* Function to get sum of digits */
    static int getSum(int n)
    {
        int sum = 0;
 
        while (n != 0) {
            sum = sum + n % 10;
            n = n / 10;
        }
 
        return sum;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 687;
        Console.Write(getSum(n));
    }
}
 
// This code is contributed by Sam007


PHP


Javascript


C++
#include 
using namespace std;
 
/* Function to get sum of digits */
class gfg {
public:
    int getSum(int n)
    {
        int sum;
 
        /* Single line that calculates sum */
        for (sum = 0; n > 0; sum += n % 10, n /= 10)
            ;
 
        return sum;
    }
};
 
// Driver code
int main()
{
    gfg g;
    int n = 687;
    cout << g.getSum(n);
    return 0;
}
// This code is contributed by Soumik


C
#include 
 
/* Function to get sum of digits */
int getSum(int n)
{
    int sum;
 
    /* Single line that calculates sum */
    for (sum = 0; n > 0; sum += n % 10, n /= 10)
        ;
 
    return sum;
}
 
// Driver code
int main()
{
    int n = 687;
    printf(" %d ", getSum(n));
    return 0;
}


Java
// Java program to compute
// sum of digits in number.
import java.io.*;
 
class GFG {
 
    /* Function to get sum of digits */
    static int getSum(int n)
    {
        int sum;
 
        /* Single line that calculates sum */
        for (sum = 0; n > 0; sum += n % 10, n /= 10)
            ;
 
        return sum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 687;
 
        System.out.println(getSum(n));
    }
}
 
// This code is contributed by Gitanjali


Python3
# Function to get sum of digits
 
 
def getSum(n):
 
    sum = 0
 
    # Single line that calculates sum
    while(n > 0):
        sum += int(n % 10)
        n = int(n/10)
 
    return sum
 
 
# Driver code
n = 687
print(getSum(n))
 
# This code is contributed by
# Smitha Dinesh Semwal


C#
// C# program to compute
// sum of digits in number.
using System;
 
class GFG {
    static int getSum(int n)
    {
        int sum;
 
        /* Single line that calculates sum */
        for (sum = 0; n > 0; sum += n % 10, n /= 10)
            ;
 
        return sum;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 687;
        Console.Write(getSum(n));
    }
}
 
// This code is contributed by Sam007


PHP
 0; $sum += $n % 10,
                                  $n /= 10);
    return $sum;
}
 
// Driver Code
$n = 687;
echo(getsum($n));
 
// This code is contributed by
// Smitha Dinesh Semwal.
?>


Javascript


C++
// C++ program to compute
// sum of digits in number.
#include 
using namespace std;
class gfg {
public:
    int sumDigits(int no)
    {
        return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
    }
};
 
// Driver code
int main(void)
{
    gfg g;
    cout << g.sumDigits(687);
    return 0;
}


C
// C program to compute
// sum of digits in number.
#include 
using namespace std;
int sumDigits(int no)
{
    return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
}
 
int main(void)
{
    printf("%d", sumDigits(687));
    return 0;
}


Java
// Java program to compute
// sum of digits in number.
import java.io.*;
 
class GFG {
 
    /* Function to get sum of digits */
    static int sumDigits(int no)
    {
        return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        System.out.println(sumDigits(687));
    }
}
 
// This code is contributed by Gitanjali


Python3
# Python program to compute
# sum of digits in number.
 
 
def sumDigits(no):
    return 0 if no == 0 else int(no % 10) + sumDigits(int(no/10))
 
 
# Driver code
print(sumDigits(687))
 
# This code is contributed by
# Smitha Dinesh Semwal


C#
// C# program to compute
// sum of digits in number.
using System;
 
class GFG {
    /* Function to get sum of digits */
    static int sumDigits(int no)
    {
        return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
    }
 
    // Driver code
    public static void Main()
    {
        Console.Write(sumDigits(687));
    }
}
 
// This code is contributed by Sam007


PHP


Javascript


C++14
// C++ implementation of the above aprroach
#include 
using namespace std;
int getSum(string str)
{
    int sum = 0;
 
    // Traversing through the string
    for (int i = 0; i < str.length(); i++) {
        // Since ascii value of
        // numbers starts from 48
        // so we subtract it from sum
        sum = sum + str[i] - 48;
    }
    return sum;
}
 
// Driver Code
int main()
{
    string st = "123456789123456789123422";
    cout << getSum(st);
    return 0;
}


Java
// Java implementation of the above aprroach
import java.io.*;
class GFG {
 
    static int getSum(String str)
    {
        int sum = 0;
 
        // Traversing through the string
        for (int i = 0; i < str.length(); i++) {
 
            // Since ascii value of
            // numbers starts from 48
            // so we subtract it from sum
            sum = sum + str.charAt(i) - 48;
        }
        return sum;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String st = "123456789123456789123422";
        System.out.print(getSum(st));
    }
}
 
// This code is contributed by Dharanendra L V.


Python3
# Python implementation of the above aprroach
def getSum(n):
    # Initializing sum to 0
    sum = 0
    # Traversing through string
    for i in n:
        # Converting char to int
        sum = sum + int(i)
 
    return sum
 
 
n = "123456789123456789123422"
print(getSum(n))


C#
// C# implementation of the above aprroach
using System;
public class GFG {
    static int getSum(String str)
    {
        int sum = 0;
 
        // Traversing through the string
        for (int i = 0; i < str.Length; i++) {
 
            // Since ascii value of
            // numbers starts from 48
            // so we subtract it from sum
            sum = sum + str[i] - 48;
        }
        return sum;
    }
 
    // Driver Code
    static public void Main()
    {
        String st = "123456789123456789123422";
        Console.Write(getSum(st));
    }
}
 
// This code is contributed by Dharanendra L V.


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check sum
// of digit using tail recursion
int sum_of_digit(int n, int val)
{
    if (n < 10)
    {
        val = val + n;
        return val;
    }
    return sum_of_digit(n / 10, (n % 10) + val);
}
 
// Driver code
int main()
{
    int num = 12345;
    int result = sum_of_digit(num, 0);
     
    cout << "Sum of digits is " << result;
     
    return 0;
}
 
// This code is contributed by subhammahato348


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class sum_of_digits {
   
    // Function to check sum
    // of digit using tail recursion
    static int sum_of_digit(int n, int val)
    {
        if (n < 10) {
            val = val + n;
            return val;
        }
        return sum_of_digit(n / 10, (n % 10) + val);
    }
 
    // Driven Program to check above
    public static void main(String args[])
    {
        int num = 12345;
        int result = sum_of_digit(num, 0);
        System.out.println("Sum of digits is " + result);
    }
}


Python3
# Python3 program for the above approach
 
# Function to check sum
# of digit using tail recursion
def sum_of_digit(n, val):
     
    if (n < 10):
        val = val + n
        return val
         
    return sum_of_digit(n // 10, (n % 10) + val)
 
# Driver code
num = 12345
result = sum_of_digit(num, 0)
 
print("Sum of digits is", result)
 
# This code is contributed by subhammahato348


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to check sum
// of digit using tail recursion
static int sum_of_digit(int n, int val)
{
    if (n < 10)
    {
        val = val + n;
        return val;
    }
    return sum_of_digit(n / 10, (n % 10) + val);
}
 
// Driver code
public static void Main()
{
    int num = 12345;
    int result = sum_of_digit(num, 0);
 
    Console.Write("Sum of digits is " + result);
}
}
 
// This code is contributed by subhammahato348


Javascript


输出
21

如何单行计算?
下面的函数具有三行而不是一行,但是它计算行中的总和。如果将指针传递给sum,则可以将其制成单行函数。

C++

#include 
using namespace std;
 
/* Function to get sum of digits */
class gfg {
public:
    int getSum(int n)
    {
        int sum;
 
        /* Single line that calculates sum */
        for (sum = 0; n > 0; sum += n % 10, n /= 10)
            ;
 
        return sum;
    }
};
 
// Driver code
int main()
{
    gfg g;
    int n = 687;
    cout << g.getSum(n);
    return 0;
}
// This code is contributed by Soumik

C

#include 
 
/* Function to get sum of digits */
int getSum(int n)
{
    int sum;
 
    /* Single line that calculates sum */
    for (sum = 0; n > 0; sum += n % 10, n /= 10)
        ;
 
    return sum;
}
 
// Driver code
int main()
{
    int n = 687;
    printf(" %d ", getSum(n));
    return 0;
}

Java

// Java program to compute
// sum of digits in number.
import java.io.*;
 
class GFG {
 
    /* Function to get sum of digits */
    static int getSum(int n)
    {
        int sum;
 
        /* Single line that calculates sum */
        for (sum = 0; n > 0; sum += n % 10, n /= 10)
            ;
 
        return sum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 687;
 
        System.out.println(getSum(n));
    }
}
 
// This code is contributed by Gitanjali

Python3

# Function to get sum of digits
 
 
def getSum(n):
 
    sum = 0
 
    # Single line that calculates sum
    while(n > 0):
        sum += int(n % 10)
        n = int(n/10)
 
    return sum
 
 
# Driver code
n = 687
print(getSum(n))
 
# This code is contributed by
# Smitha Dinesh Semwal

C#

// C# program to compute
// sum of digits in number.
using System;
 
class GFG {
    static int getSum(int n)
    {
        int sum;
 
        /* Single line that calculates sum */
        for (sum = 0; n > 0; sum += n % 10, n /= 10)
            ;
 
        return sum;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 687;
        Console.Write(getSum(n));
    }
}
 
// This code is contributed by Sam007

的PHP

 0; $sum += $n % 10,
                                  $n /= 10);
    return $sum;
}
 
// Driver Code
$n = 687;
echo(getsum($n));
 
// This code is contributed by
// Smitha Dinesh Semwal.
?>

Java脚本


输出
21

2.递归
感谢Ayesha提供以下递归解决方案。

C++

// C++ program to compute
// sum of digits in number.
#include 
using namespace std;
class gfg {
public:
    int sumDigits(int no)
    {
        return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
    }
};
 
// Driver code
int main(void)
{
    gfg g;
    cout << g.sumDigits(687);
    return 0;
}

C

// C program to compute
// sum of digits in number.
#include 
using namespace std;
int sumDigits(int no)
{
    return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
}
 
int main(void)
{
    printf("%d", sumDigits(687));
    return 0;
}

Java

// Java program to compute
// sum of digits in number.
import java.io.*;
 
class GFG {
 
    /* Function to get sum of digits */
    static int sumDigits(int no)
    {
        return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        System.out.println(sumDigits(687));
    }
}
 
// This code is contributed by Gitanjali

Python3

# Python program to compute
# sum of digits in number.
 
 
def sumDigits(no):
    return 0 if no == 0 else int(no % 10) + sumDigits(int(no/10))
 
 
# Driver code
print(sumDigits(687))
 
# This code is contributed by
# Smitha Dinesh Semwal

C#

// C# program to compute
// sum of digits in number.
using System;
 
class GFG {
    /* Function to get sum of digits */
    static int sumDigits(int no)
    {
        return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
    }
 
    // Driver code
    public static void Main()
    {
        Console.Write(sumDigits(687));
    }
}
 
// This code is contributed by Sam007

的PHP


Java脚本


输出
21

3.将输入作为字符串

当该数字的位数超过10 19时,由于long long int的范围不满足给定的数字,我们不能将该数字作为整数。因此,将输入作为字符串,从开头到字符串的长度运行循环,并使用该字符增加和(在这种情况下为数字)

下面是上述方法的实现

C++ 14

// C++ implementation of the above aprroach
#include 
using namespace std;
int getSum(string str)
{
    int sum = 0;
 
    // Traversing through the string
    for (int i = 0; i < str.length(); i++) {
        // Since ascii value of
        // numbers starts from 48
        // so we subtract it from sum
        sum = sum + str[i] - 48;
    }
    return sum;
}
 
// Driver Code
int main()
{
    string st = "123456789123456789123422";
    cout << getSum(st);
    return 0;
}

Java

// Java implementation of the above aprroach
import java.io.*;
class GFG {
 
    static int getSum(String str)
    {
        int sum = 0;
 
        // Traversing through the string
        for (int i = 0; i < str.length(); i++) {
 
            // Since ascii value of
            // numbers starts from 48
            // so we subtract it from sum
            sum = sum + str.charAt(i) - 48;
        }
        return sum;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String st = "123456789123456789123422";
        System.out.print(getSum(st));
    }
}
 
// This code is contributed by Dharanendra L V.

Python3

# Python implementation of the above aprroach
def getSum(n):
    # Initializing sum to 0
    sum = 0
    # Traversing through string
    for i in n:
        # Converting char to int
        sum = sum + int(i)
 
    return sum
 
 
n = "123456789123456789123422"
print(getSum(n))

C#

// C# implementation of the above aprroach
using System;
public class GFG {
    static int getSum(String str)
    {
        int sum = 0;
 
        // Traversing through the string
        for (int i = 0; i < str.Length; i++) {
 
            // Since ascii value of
            // numbers starts from 48
            // so we subtract it from sum
            sum = sum + str[i] - 48;
        }
        return sum;
    }
 
    // Driver Code
    static public void Main()
    {
        String st = "123456789123456789123422";
        Console.Write(getSum(st));
    }
}
 
// This code is contributed by Dharanendra L V.

Java脚本


输出

104

4.使用尾递归

也可以使用尾递归来解决此问题。这是解决问题的一种方法。

1.向函数添加另一个变量“ Val”,并将其初始化为(val = 0)

2.在每次调用该函数,将mod值(n%10)添加到变量“(n%10)+ val”中,这是n中的最后一位。随同传递变量n为n / 10。

3.因此,在“首次呼叫”中,它将具有最后一位数字。当我们以n / 10的形式传递n / 10时,直到n减小到一位为止。

4. n <10是基本情况,因此当n <10时,将n添加到变量中,因为它是最后一位数字,并返回将具有数字总和的val

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to check sum
// of digit using tail recursion
int sum_of_digit(int n, int val)
{
    if (n < 10)
    {
        val = val + n;
        return val;
    }
    return sum_of_digit(n / 10, (n % 10) + val);
}
 
// Driver code
int main()
{
    int num = 12345;
    int result = sum_of_digit(num, 0);
     
    cout << "Sum of digits is " << result;
     
    return 0;
}
 
// This code is contributed by subhammahato348

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class sum_of_digits {
   
    // Function to check sum
    // of digit using tail recursion
    static int sum_of_digit(int n, int val)
    {
        if (n < 10) {
            val = val + n;
            return val;
        }
        return sum_of_digit(n / 10, (n % 10) + val);
    }
 
    // Driven Program to check above
    public static void main(String args[])
    {
        int num = 12345;
        int result = sum_of_digit(num, 0);
        System.out.println("Sum of digits is " + result);
    }
}

Python3

# Python3 program for the above approach
 
# Function to check sum
# of digit using tail recursion
def sum_of_digit(n, val):
     
    if (n < 10):
        val = val + n
        return val
         
    return sum_of_digit(n // 10, (n % 10) + val)
 
# Driver code
num = 12345
result = sum_of_digit(num, 0)
 
print("Sum of digits is", result)
 
# This code is contributed by subhammahato348

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to check sum
// of digit using tail recursion
static int sum_of_digit(int n, int val)
{
    if (n < 10)
    {
        val = val + n;
        return val;
    }
    return sum_of_digit(n / 10, (n % 10) + val);
}
 
// Driver code
public static void Main()
{
    int num = 12345;
    int result = sum_of_digit(num, 0);
 
    Console.Write("Sum of digits is " + result);
}
}
 
// This code is contributed by subhammahato348

Java脚本


输出
Sum of digits is 15
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。