Advertisement
Spocoman

02. Sum Digits

Oct 17th, 2024 (edited)
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.82 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. class Main {
  4.     public static void main(String[] args) {
  5.         Scanner scanner = new Scanner(System.in);
  6.         int number = Integer.parseInt(scanner.nextLine()),
  7.             sumDigits = 0;
  8.            
  9.         while (number > 0) {
  10.             sumDigits += number % 10;
  11.             number /= 10;
  12.         }
  13.        
  14.         System.out.println(sumDigits);
  15.     }
  16. }
  17.  
  18. OR:
  19.  
  20. import java.util.Scanner;
  21.  
  22. class Main {
  23.     public static void main(String[] args) {
  24.         Scanner scanner = new Scanner(System.in);
  25.         String number = scanner.nextLine();
  26.         int sumDigits = 0;
  27.            
  28.         for (int i = 0; i < number.length(); i++) {
  29.             sumDigits += Character.getNumericValue(number.charAt(i));
  30.         }
  31.        
  32.         System.out.println(sumDigits);
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement