代码(可以通过,不过很乱,需要整理):
/// <summary> /// 计算n在数组[targetNum]中出现的次数 /// 形如:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] /// </summary> /// <param name="targetNum"></param> /// <param name="n"></param> /// <returns></returns> public static int GetCount(int targetNum, int n) { int count = 0; if (n > 0 && n <= 9) { int ratio = 10; while (true) { int tmp = targetNum/ratio * ratio; if (tmp > 0) { count += tmp / 10; } int tmpA = targetNum - tmp; if (ratio == 10) { if (tmpA >= n) { count++; } } else { int tmpB = tmpA/(ratio/10); if (tmpB > n) { count += 1*(ratio/10); } else if (tmpB == n) { count += tmpA%(ratio/10) + 1; } } ratio *= 10; if (tmp == 0) { break; } } } else if (n == 0) { int ratio = 10; while (true) { int tmp = targetNum / ratio * ratio; if (tmp > 0) { count += tmp / 10; } int tmpA = targetNum - tmp; if (tmpA == targetNum) { if (tmpA > 100) { count -= ratio/10/10; } else if (ratio == 10) { count = 1; } break; } if (ratio == 10) { if (tmpA >= n) { count++; } } else { int tmpB = tmpA / (ratio / 10); if (tmpB > n) { count += 1 * (ratio / 10); } else if (tmpB == n) { count += tmpA % (ratio / 10) + 1; } } ratio *= 10; } } return count; }