Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

程序题:java程序统计1到1000出现几个1

$
0
0

java程序实现1到1000出现几个1 

不废话,直接上代码,需要的可以直接拷走:

 

/**
 * java程序实现1到1000出现几个1  
 * @author hbxfyxw
 * @blog   http://blog.csdn.net/hbxfyxw
 */
public class CountNum {
	public static void main(String[] args) {
		StringBuffer str = new StringBuffer();  
		for (int i = 1; i <= 1000; i++) {   
			str.append(i);  
			}  
		String str2 = str.toString();    
		str2 = str2.replaceAll("[0|2|3|4|5|6|7|8|9]", "");    
		System.out.println(str2.length()); 
	}
}


 如果不是程序题的话,可以这样想:

 

1-9:1个 10-19:11个 20-99:8个 总共1+11+8=20(1-99)
100开始,每个数必有一个1,故而100-199中,1的个数等于100+20(1-99中1的个数)=120
200-299中1的个数和1-99中1的个数一样,为20个。
同理300-399:20
400-499:20
500-599:20
。。。
共有20X9+120+1(1000含有一个1)=301个


 

作者:hbxfyxw 发表于2013-4-6 23:11:09 原文链接
阅读:120 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>