Approach 1:
Repeated division-modulus operations:
long num = 123456789; int count = 0; while(num > 0) { int digit = num % 10; if(digit == 1) count ++; num /= 10; } Approach 2:
Convert it into an String and get the characters at the position:
long num = 123456789; int count = 0; String s = String.valueOf(num); for(int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if(ch == '1') count ++; } The second operation doesn't need to get the remainder and the quotient each time. A charAt() method can be enough.
Which approach is considered to be better and why?
Consider taking the input from the console.
1st Case:
long num = scanner.nextLong(); 2nd Case:
String s = scanner.nextLine(); Here there would be no overhead on converting the number to string.
Also let us assume it is for positive numbers.
1s? Would this be used in a method with the signatureprivate static int countOccurrence(int number, int searchFor)? \$\endgroup\$