#yyds干货盘点# LeetCode程序员面试金典:出现的次数

时间:2021-06-03 00:56:37

题目:

编写一个方法,计算从 0 到 n (含 n) 中数字 2 出现的次数。

示例:

输入: 25

输出: 9

解释: (2, 12, 20, 21, 22, 23, 24, 25)(注意 22 应该算作两次)

代码实现:

class Solution {
public int numberOf2sInRange(int n) {
if (n < 2) {
return 0;
}
int[] cntOf2ByCnt = new int[11];
int[] cntByNum = new int[11];
cntByNum[1]=1;
int tmp = 1;
for (int i = 2; i < 11; i++) {
cntOf2ByCnt[i] = (i - 1) * tmp;
tmp = tmp * 10;
cntByNum[i] = tmp;
}

String str = String.valueOf(n);
int result = 0;
for (int i = 0; i < str.length(); i++) {
int idx = str.length() - i - 1;
int cnt = i + 1;
int x = str.charAt(idx) - '0';

result = result + x * cntOf2ByCnt[cnt];
if (str.charAt(idx) == '2') {
String tmpStr = str.substring(idx + 1);
int tmpNum=0;
if(!"".equals(tmpStr)) {
tmpNum=Integer.valueOf(tmpStr);
}
result = result + tmpNum + 1;
} else if (str.charAt(idx) > '2') {
result = result + cntByNum[cnt];
}
}

return result;
}
}