sunfresh

Sum Digits

Jan 20th, 2023
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. Sum Digits
  2. Write a program that reads a four-digit number and displays the sum of its digits
  3.  
  4. 1213 => 1 + 2 + 1 + 3 = 7
  5. 2346 => 2 + 3 + 4 + 6 = 15
  6. Input
  7. On the first line, you will receive the four-digit number N
  8. Output
  9. On the only line of output, print the sum of digits
  10. Constraints
  11. 1000 <= N <= 9999
  12. Input
  13. 2346
  14. Output
  15. 15
  16.  
  17. import java.util.Scanner;
  18.  
  19. public class sumDigits {
  20. public static void main(String[] args) {
  21. Scanner scanner = new Scanner(System.in);
  22. int n = Integer.parseInt(scanner.nextLine());
  23. System.out.println(sum(n));
  24. }
  25.  
  26. public static int sum(int n) {
  27. if (n == 0) {
  28. return 0;
  29. }
  30. return n % 10 + sum(n / 10);
  31. }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment