Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Count occurrences 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.
- 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).
- Input
- On the first line you will be given n.
- Output
- On the only output line you should print the count of 8s.
- Constraints
- n>=0
- Sample tests
- Input
- 8
- Output
- 1
- Input
- 818
- Output
- 2
- import java.util.Scanner;
- public class CountOccurrences2 {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int input = Integer.parseInt(scanner.nextLine());
- System.out.println(numberOfOccurrences(input));
- }
- public static int numberOfOccurrences(int n){
- int count = 0;
- if(n < 10 && n != 8){
- return count;
- }
- if(n%10==8){
- count++;
- if(n/10 % 10 == 8){
- count++;
- }
- }
- return count + numberOfOccurrences(n/10);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment