Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Add all digits of a number program

Posted on January 26, 2022January 26, 2022 by admin

Overview

The objective is to repeatedly add all digits of a number until the result is only a single digit.

For example

Input: 453
Step 1: 4+5+3 = 12
Step 2: 1+2 =3

Output: 3

Another example

Input: 45
Step 1: 4+5 = 9

Output: 9

Program

Here is the program for the same

package main

import "fmt"

func addDigits(num int) int {

	if num < 10 {
		return num
	}

	for num > 9 {
		num = sum(num)
	}

	return num

}

func sum(num int) int {
	output := 0
	for num > 0 {
		output = output + num%10
		num = num / 10
	}
	return output
}

func main() {
	output := addDigits(453)
	fmt.Println(output)

	output = addDigits(45)
	fmt.Println(output)

}

Output

3
9
©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme