您的位置:首页 > Web前端

《剑指offer》-任意非负整数区间中1出现的次数

2018-01-27 14:22 218 查看
/*
* 求出1~13的整数中1出现的次数,1~13中包含1的数字有1、10、11、12、13,因此共出现6次,
* 很快的求出任意非负整数区间中1出现的次数。
*/
public class NumberOf1Between1AndN_Solution {
//将数字转化成字符串,判断字符串中包含多少个1
public int numberOf1Between1AndN_Solution(int n) {
int count = 0;
for(int i = 1;i <= n;i ++) {
String str = String.valueOf(i);
for(int j = 0;j < str.length();j ++) {
if(str.charAt(j) == '1') {
count ++;
}
}
}

return count;
}

/*数字不断对10取余,判断余数是否为1
*注:如果有n个数,则整体算法复杂度O(nlogn)以10为底
*/
public int numberOf1Between1AndN_Solution2(int n) {
int count = 0;
for(int i = 1;i <= n;i ++) {
int temp = i;
while(temp != 0) {
if(temp % 10 == 1) {
count ++;
}
temp = temp / 10;
}
}

return count;
}

public static void main(String[] args) {
System.out.println(new NumberOf1Between1AndN_Solution().numberOf1Between1AndN_Solution2(13));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐