思路:對於整數中出現1的次數,可以考慮利用取餘和除法運算來求得。採用暴力循環。
對每一個數的每一位利除10取餘來取得
對於任何數字出現的次數都可以利用這種方法求得,只不過餘數要等於對應的數字X;
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n)
{
int temp;
int count=0;
for(int i=1;i<=n;i++)
{
temp=i;
while(temp!=0){
if(temp%10==1)
count++;
temp/=10;
}
}
return count;
}
};
一種高效的算法:
ublic int NumberOf1Between1AndN_Solution2(int n) {
int count = 0;
for (int i = 1; i <= n; i *= 10) {
int a = n / i,b = n % i;
//之所以補8,是因爲當百位爲0,則a/10==(a+8)/10,
//當百位>=2,補8會產生進位位,效果等同於(a/10+1)
count += (a + 8) / 10 * i + ((a % 10 == 1) ? b + 1 : 0);
}
return count;
}
對於n的階乘中末尾0的個數問題:
階乘中出現0,可以歸根於2*5;而n的階乘中2的個數遠遠大於5的個數,所以只要求出5的個數就可以知道末尾0的個數。
對於5的個數可以採用暴力循環的方法:
for (int i = 5; i <= n; i+=5)
{
int j = i;
while (j % 5 == 0)
{
count++;
j /= 5;
}
}
當然也可以根據規律:5中5的個數爲1,10,15,20中5的個數爲1,但25,125中5的個數爲2,3.故25 的階乘中5的個數爲:6
故N中5的個數爲:n=N/5+N/(5^2)+N/(5^3)....+N/(5^k) (k<=N/5)
while(n>0){
count+=n/5;
n=n/5;
}