sunfresh

Count occurrences

Jan 20th, 2023
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. Count occurrences
  2. Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example 717 yields 2. (no loops).
  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 7s.
  11.  
  12. Constraints
  13. n>=0
  14.  
  15. Sample tests
  16. Input
  17. 717
  18. Output
  19. 2
  20. Input
  21. 7
  22. Output
  23. 1
  24.  
  25. import java.util.Scanner;
  26.  
  27. public class CountOccurrences {
  28. public static void main(String[] args) {
  29. Scanner scanner = new Scanner(System.in);
  30. String input = scanner.nextLine();
  31. System.out.println(result(input, '7'));
  32. }
  33.  
  34. public static int result(String n, char c ) {
  35. int count = 0;
  36. if (n.length() > 0) {
  37. if (n.charAt(0) == c) {
  38. count++;
  39. }
  40. count += result(n.substring(1), c);
  41. }
  42. return count;
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment