Amazon Interview Question
Software Engineer in TestsMay not accept numbers with size larger than 12 digits.. But that can be handled..
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Summation {
public static void main(String[] args) throws IOException {
System.out.println("Enter the Number:");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String snum = in.readLine();
long num = Integer.parseInt(snum);
while (size(num) != 1) {
num = addDigits(num);
}
System.out.println("Ans:" + num);
}
public static long addDigits(long num) {
long numOfDigits = size(num);
int startMod = 10;
long sum = 0;
for(int i = 0; i < numOfDigits; i++){
long digit = num%startMod;
sum = sum + digit;
num = (int) num/startMod;
}
return (sum);
}
public static long size(long num) {
int digits = 0;
int step = 1;
while (step <= num) {
digits++;
step = step * 10;
}
return (digits);
}
}
The above code is correct, except it should simply return sum, instead of recursively calling the function .
No, if we just return sum for
789 --> 7+8+9 = 24
it will return 24
the answer is
2+4 = 6
So, recursively we have to call the same function again.
int recursiveSum(int num)
{
if(num % 10 == num)
return num;
int lastDigit = num % 10;
int remainder = num / 10;
return (lastDigit + recursiveSum(remainder);
}
Time Complexity: O(n).
PS: If there is anything wrong with the code, feel free to correct me ...
This is number nine trick. Ans=(Number)%9
- Tulley April 28, 2011Proof I don't know.