剑指offer--第43题 1~n整数中1出现的次数

题目输入一个整数n,求1-n这n个整数的十进制表示中1出现的次数。例如,输入12,1-12这些整数中包含1的数字有1、10、11和12,1共出现了5次。
剑指offer思路 循环取余,其实也有另外一种找规律的思路,可是一般情况我可能想不到。
注意这里是说1出现的次数,不是 1出现的整数的个数。

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
     if(n<=0) {
			 return 0;
		 }
		 int count =0 ;//记录总个数;
		    for(int i=1;i<=n;i++ ) {
		    	int temp = i;
		    	while(temp!=0) {
		    		int remainder = 0;//余数;
		    		remainder = temp%10;
		    		temp = temp/10;
		    		if(remainder==1) {
		    			count++;
		    		}
		    	}
		    }
		    return count;
    }
}
多思考,多尝试。
原文地址:https://www.cnblogs.com/LynnMin/p/9368321.html