标签:
给定一个十进制数N,写下从1开始,到N的所有整数,然后数一下其中出现的所有”1“的个数。
例如N=2,写下1,2。这样只出现了1个”1“.
public int getNumberOfOne(int n){ int factor =1 ; int count = 0; while(n/factor!=0){ int lowerNumber = n-(n/factor)*factor; int currentNumber = (n/factor)%10; int highNumber = n/(factor*10); switch(currentNumber){ case 0: count += highNumber*factor; break; case 1: count+=highNumber*factor+lowerNumber+1; break; default: count+=(highNumber+1)*factor; break; } factor *= 10; } return count; }
标签:
原文地址:http://www.cnblogs.com/yingpu/p/5851844.html