Sum of the digits of a given number

Posted by N.K. Chauhan on Mar 31, 2024

A number n is given, the task is to find sum of its digits.

Example 1: Find Sum of the digits of 1000

Input: 1000
Output: 1

Example 2: Find Sum of the digits of 0

Input: 0
Output: 0

Example 1: Find Sum of the digits of 1234

Input: 1234
Output: 10

Example 1: Find Sum of the digits of 5

Input: 5
Output: 5


Solutions

Method 1: Recursion

If we take modulo(%) of a number by 10 we get the last digit of that number i.e. 123 % 10 = 3; similarly if we divide a number by 10 and store the value in int we get the number except last digit i.e. int r = 123 / 10 = 12.

Sum of digit "0" is "0", this will make the base condition, we will keep separating last digit from the number until the number is completely traversed. In each recursive call add last digit with sum of remaining digits.

package com.cb.recursion;

/*
* Recursion
* */
public class R16_SumOfDigits {
    public static int sum(int digits) {

        // all digits are exhausted or 0
        if (digits <= 0)
            return 0;

        // add current digit with sum(remainingDigits)
        return digits % 10 + sum(digits / 10);
    }

    public static void main(String[] args) {
        System.out.println(sum(1000));
        System.out.println(sum(1234));
        System.out.println(sum(0));
        System.out.println(sum(1));
    }
}
1
10
0
1

Complexity

The time complexity of this solution is O(n) and space complexity is O(1).

Related


Write a program to reverse a string

Print numbers from 0 to a given number

Check if an integer array is sorted or not

Program for printing nth Fibonacci Number

Calculate the Power of a Number (n^p)

Print spelling for a given number

Program to solve "Tower of Hanoi" problem

Print numbers from a given number to 0

Calculate factorial of a given number

Count ways to reach the nth stair