算法题:1的数目

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Bubble1210/article/details/50927148

给定一个十进制正整数N,写下从1开始,到N的所有正整数,然后数一下其中出现的所有“1”的个数。例如:N =12,我们会写下1,2,3,4,5,6,7,8,9,10,11,12。这样1出现的个数为5

java代码实现

public class demo1 {

	public static void main(String[] args) {
		Sum sum = new Sum();
		System.out.println("请输入一个正整数N:");
		int v = new Scanner(System.in).nextInt();
		System.out.println("从1开始,到N的所有整数,1出现的个数:" + sum.sum1(v));
	}
}
class Sum{
	public int sum1(int n){
		int count = 0;
		int factor =1;
		int lowerNum = 0;
		int currNum = 0;
		int higherNum = 0;
		while(n/factor !=0){
			lowerNum = n-(n/factor)*factor;
			currNum = (n/factor)%10;
			higherNum = n/(factor*10);
			switch(currNum){
			case 0:
				count +=higherNum*factor;
				break;
			case 1:
				count +=higherNum*factor+lowerNum+1;
				break;
			default:
				count +=(higherNum+1)*factor;
				break;
			}
			factor *=10;
		}
		return count;
	}
}
运行结果:请输入一个正整数N:
256
从1开始,到N的所有整数,1出现的个数:156

猜你喜欢

转载自blog.csdn.net/Bubble1210/article/details/50927148
今日推荐