public class Solution {
//一、找规律的解法
public int NumberOf1Between1AndN_Solution(int n) {
if(n<=0)
return 0;
if(n<10)
return 1;
int re=0;
for(long m=1;m<=n;m*=10)
re+=(n/m+8)/10*m+((n/m%10==1)?1:0)*(n%m+1);
return re;
}
//二、暴力解法
public int NumberOf1Between1AndN_Solution2(int n) {
if(n<=0)
return 0;
if(n<10)
return 1;
int count=0;
for(int i=1;i!=n+1;i++)
{
String str=String.valueOf(i);
for(int j=0;j!=str.length();j++)
{
if(str.charAt(j)=='1')
count++;
}
}
return count;
}
public static void main(String[]args){
//System.out.println("Hello");
Solution s=new Solution();
System.out.println(s.NumberOf1Between1AndN_Solution2(100000000));
}
}
判断给定数字中1的个数
最新推荐文章于 2024-10-04 22:51:40 发布