Java Program to Find Sum of Digits in a Number using Recursion - Interview Question

Recently this question to asked was one of my reader, which inspired me to write this tutorial. There was usual check to solve this problem using both recursion and iteration. To be frank, calculating sum of digit of an integral number, is not difficult, but I have still seen quite a few programmers fumbles, even after providing hint in terms of division and modules operator. Key point here is to know how to use division and modules operator in Java. For this kind of exercise including reversing a number, where you need to find digits from a number, use division operator to remove right, and use modules operator or % to get right most digits. For example if you have number 1234 than 1234/10 will give you 123 i.e. right most digit 4 is removed, while 1234%10 will give you 4, which is the right most digit in that number. If you know this property, you can easily solve lots or problems which are related to reversing numbers e.g. checking if a number is palindromeor finding Armstrong numbers in Java.
Read more »

0 Response to "Java Program to Find Sum of Digits in a Number using Recursion - Interview Question"

Posting Komentar