sunfresh

Count occurrences 2

Jan 20th, 2023
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. Count occurrences 2
  2. Given a non-negative int n, compute recursively (no loops) the count of the occurrences of 8 as a digit, except that an 8 with another 8 immediately to its left counts double, so 8818 yields 4.
  3.  
  4. Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
  5.  
  6. Input
  7. On the first line you will be given n.
  8.  
  9. Output
  10. On the only output line you should print the count of 8s.
  11.  
  12. Constraints
  13. n>=0
  14.  
  15. Sample tests
  16. Input
  17. 8
  18. Output
  19. 1
  20. Input
  21. 818
  22. Output
  23. 2
  24.  
  25. import java.util.Scanner;
  26.  
  27. public class CountOccurrences2 {
  28. public static void main(String[] args) {
  29. Scanner scanner = new Scanner(System.in);
  30. int input = Integer.parseInt(scanner.nextLine());
  31. System.out.println(numberOfOccurrences(input));
  32. }
  33.  
  34. public static int numberOfOccurrences(int n){
  35. int count = 0;
  36. if(n < 10 && n != 8){
  37. return count;
  38. }
  39. if(n%10==8){
  40. count++;
  41. if(n/10 % 10 == 8){
  42. count++;
  43. }
  44. }
  45. return count + numberOfOccurrences(n/10);
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment