public class RecursiveSum { public static int sumOfDigits(int number) { System.out.println("Called"); if(number/10 == 0) return number; return number%10 + sumOfDigits(number/10); } public static int sumOfDigitsIterative(int number) { int result = 0; while(number != 0) { result = result + number%10; number = number/10; } return result; } public static void main(String[] args) { System.out.println(sumOfDigits(3000)); System.out.println(sumOfDigitsIterative(123)); } } Output: Called Called Called Called 3 6
Search This Blog
Labels
- Apache Http Client (4)
- Array (3)
- Array List (12)
- Assertion (2)
- Calendar (20)
- Collection (7)
- Common Sol (14)
- Core Java (36)
- Date (4)
- Design Pattern (2)
- Display Tag (4)
- Eclipse (3)
- Enum (2)
- Exception Handling (5)
- How To (6)
- HttpURLConnection (2)
- ImageIO (2)
- Inner Class (1)
- Java Interview Q (1)
- Java IO (6)
- Java Mail (4)
- JDBC (1)
- JSON (5)
- JSP (2)
- JSTL (2)
- MYSQL (1)
- Platform Environment (3)
- Reg Ex (1)
- Serialization (1)
- Servers (3)
- Servlet JSP (3)
- Singleton Pattern (2)
- SQL (2)
- String Handling (11)
- Struts (5)
- Synchronization (5)
- Threads (6)
- Web Services (3)
0 comments:
Post a Comment