Given a list L of numbers from 0 to n, and another number k = [0-9], find how many times k appears in L. If the target number in L is more than one digit, treat each digit separately. For example, k=0 appears twice in L = [0,10].

Java Solution:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package array; public class TotalOccurrences { static int count = 0; public static void main(String[] args) { // TODO Auto-generated method stub int number[] = {1,2,3,4,5,6,7,8,9,2,23}; int k = 2; getTotalOccurrences(number, k); System.out.println("Total count is "+count); } private static void getTotalOccurrences(int[] number, int k) { for(int num : number) { System.out.println(num); if(num < 9 && num == k) { count++; } else { if(num%10 == k) { count++; } int remaining = num/10; if(remaining == k) { count++; } } } } } |

Output:

Total count is 3