desislava_topuzakova

02. Sum Digits

Sep 24th, 2021
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. package Test;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class SumDigits_02 {
  6. public static void main(String[] args) {
  7. Scanner scanner = new Scanner(System.in);
  8. int number = Integer.parseInt(scanner.nextLine());
  9. int sum = 0; //сума от цифрите
  10. //number % 10 -> последната цифра на числото
  11. //повтаряме: while
  12. //1. взимаме последната цифра
  13. //2. сумираме цифрата
  14. //3. премахвам последната цифра от числото -> number / 10
  15. //stop: number == 0
  16. //continue: number != 0
  17. while (number != 0) {
  18. int lastDigit = number % 10;
  19. sum += lastDigit;
  20. number = number / 10; //number /= 10;
  21. }
  22.  
  23. System.out.println(sum);
  24. }
  25. }
  26.  
Advertisement
Add Comment
Please, Sign In to add comment