Sum of digits in a given number

Beginner Problems Basic Recursion Easy
  • This type of programming problem underlies many applications which need numeric validation, data integrity checks or compression tasks
  • For example, control digit computation, often used for credit cards number or ISBN code validation, implements similar logic
  • This problem's concept is also useful in checksum algorithms in data transmission to ensure data completeness
  • Also, digital root calculation, which is the essence of this task, is a part of various cryptographic techniques and pseudorandom number generation systems, fundamental for security and gaming software respectively

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Examples:

Input : num = 529

Output : 7

Explanation : In first iteration the digits sum will be = 5 + 2 + 9 => 16

In second iteration the digits sum will be 1 + 6 => 7.

Now single digit is remaining , so we return it.

Input : num = 101

Output : 2

Explanation : In first iteration the digits sum will be = 1 + 0 + 1 => 2

Now single digit is remaining , so we return it.

Input : num = 38

Constraints

  • 0 <= num <= 231 - 1

Company Tags

TCS Cognizant Accenture Infosys Capgemini Wipro IBM HCL Tech Mahindra MindTree