📜  Java程序对给定数字的数字求和

📅  最后修改于: 2022-05-13 01:58:09.626000             🧑  作者: Mango

Java程序对给定数字的数字求和

给定一个数,求其位数之和。
例子 :

Input : n = 687
Output : 21

Input : n = 12
Output : 3

1. 迭代:

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 program
    public static void main(String[] args)
    {
        int n = 687;
 
        System.out.println(getSum(n));
    }
}
 
// This code is contributed by Gitanjali


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


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)
    {
    int n = 687;
 
    System.out.println(sumDigits(n));
    }
}
 
// This code is contributed by Gitanjali


时间复杂度: O(|n|)

辅助空间: O(1)

如何单行计算?

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

时间复杂度: O(|n|)

辅助空间: O(1)

2.递归

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)
    {
    int n = 687;
 
    System.out.println(sumDigits(n));
    }
}
 
// This code is contributed by Gitanjali

时间复杂度: O(log 10 n)

辅助空间: O(log 10 n)

有关详细信息,请参阅有关对给定数字求和的完整文章!