Open ErSKS opened 5 years ago
package countdigit;
/**
@College: Khwopa College of Engineering */ public class CountDigit {
public static void main(String[] args) { System.out.println("Count Digit 2 in 2343241 :" + countDigit(2343241, 2)); System.out.println("Count Digit 6 in 9833475 :" + countDigit(9833475, 6)); System.out.println("Count Digit 7 in 903458 :" + countDigit(903458, 7)); System.out.println("Count Digit 4 in 39485 :" + countDigit(39485, 4)); System.out.println("Count Digit 6 in 32535 :" + countDigit(32535, 6)); System.out.println("Count Digit 9 in 0 :" + countDigit(0, 9)); System.out.println("Count Digit 2 in -3525 :" + countDigit(-3525, 2)); System.out.println("Count Digit 4 in -3525235 :" + countDigit(-3525235, 4)); }
private static int countDigit(int n, int digit) { int count = 0; if (n < 0 || digit < 0) { return -1; } while (n > 0) { if (n % 10 == digit) { count++; } n /= 10; } return count; } }
CoreTask#3: CountDigits - Write a function named countDigit that returns the number of times that a given digit appears in a positive number. For example countDigit(32121, 1) would return 2 because there are two 1s in 32121. Other examples: countDigit(33331, 3) returns 4 countDigit(33331, 6) returns 0 countDigit(3, 3) returns 1 The function should return -1 if either argument is negative, so countDigit(-543, 3) returns -1. The function signature is int ountDigit(int n, int digit) Hint: Use modulo base 10 and integer arithmetic to isolate the digits of the number.