/** * @param input 整数n(1 ≤ n ≤ 1,000,000,000) * @return 1-9中某个数字在数列中出现的次数 */ public int calcCount(int input, int x) { int count = 0; int temp; // 依次从个位往上开始计算 for (int i = 1; (temp = input / i) != 0; i *= 10) { count += (temp / 10) * i; int current = temp % 10; if (current > x) { // 还会出现i次 count += i; } else if (current == x) { // (input - temp * i)表明当前位置的低位数字 count += input - temp * i + 1; } } Log.d(TAG, "calcCount() called with: input = [" + input + "], count = [" + count + "]"); return count; }
/** * @param input 整数n(1 ≤ n ≤ 1,000,000,000) * @return 0在数列中出现的次数 */ public int calcZeroCount(int input) { int count = 0; int temp; // 依次从个位往上开始计算,至最高位-1为止 for (int i = 1; (temp = input / i) / 10 != 0; i *= 10) { count += (temp / 10) * i; if (temp % 10 == 0) { // (input - temp * i)表明当前位置的低位数字,去除首位为0的数字 count += input - temp * i + 1 - i; } } return count; }
public int count(int input, int x) { int count = 0; int temp; // 依次从个位往上开始计算 for (int i = 1; (temp = input / i) != 0; i *= 10) { // 高位数字 int high = temp / 10; if (x == 0) { if (high != 0) { high--; } else { break; } } count += high * i; int current = temp % 10; if (current > x) { count += i; } else if (current == x) { // (input - temp * i)表明当前位置的低位数字 count += input - temp * i + 1; } } Log.d(TAG, "count() called with: input = [" + input + "], count = [" + count + "]"); return count; }