Wednesday, September 2, 2015

Add Digits - Given a non-negative integer number, repeatedly add all its digits until the result has only one digit.

Given a non-negative integer number, repeatedly add all its digits until the result has only one digit. 
For example,


38 = 3 + 8 = 11 = 1 + 1 = 2
58 = 5 + 8 = 13 = 1 + 3 = 4
Solution:
There are several ways to implement. Easiest way is number % 9. For example 38 % 9 = 2

Program:
package com.ranga.puzzales;

/**
* Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
* For example,
*
* 38 = 3 + 8 = 11 = 1 + 1 = 2
* 58 = 5 + 8 = 13 = 1 + 3 = 4
*
* @author Ranga Reddy
* @version 1.0
*/

public class AddDigits {
public static void main(String[] args) {
int num = 38;
int digit = 0;

// way 1
System.out.println("Finding the Single Digit using Way1 ");
digit = getSingleDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

System.out.println();

num = 58;
digit = getSingleDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

System.out.println();

num = 8;
digit = getSingleDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

System.out.println();

// Way 2
num = 38;
System.out.println("Finding the Single Digit using Way2 ");
digit = getOneDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

System.out.println();

num = 58;
digit = getOneDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

System.out.println();

num = 8;
digit = getOneDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

}

/**
* Way 1
* Used to find out the single digit.
* @param num
* @return the single digit
*/

private static int getSingleDigit(int num) {
int sum = 0;
while(num > 9) {
sum = sum + (num % 10);
num = num / 10;
}
sum = sum + num;
if(sum > 9) {
sum = getSingleDigit(sum);
}
return sum;
}

/**
* Way 2
* Used to find out the single digit.
* @param num
* @return the single digit
*/

private static int getOneDigit(int num) {
if(num == 0) return 0;
if(num % 9 == 0) return 9;
return num % 9;
}
}
Output:
Finding the Single Digit using Way1 
Input : 38, Output: 2
Input : 58, Output: 4
Input : 8, Output: 8
Finding the Single Digit using Way2 
Input : 38, Output: 2
Input : 58, Output: 4
Input : 8, Output: 8

0 comments: