标签:
一.题目
# include <iostream> using namespace std; # include <math.h> int Count1Num(int Digit) { int figure = 1; //标记计数1的位数 int curOfDigit = 0; //当前位数字 int lowerOfDigit = 0; //较低位数字 int higherOfDigit = 0; //较高位数字 int count = 0; while(Digit / figure != 0) { //取数字 curOfDigit = (Digit / figure) % 10; lowerOfDigit = Digit - (Digit / figure * figure); higherOfDigit = Digit / (figure * 10); if(Digit <= 0) return 0; if(0 == curOfDigit) //当前数字为0时计数 { count += higherOfDigit * figure; } else if(1 == curOfDigit) //当前数字为1时计数 { count += higherOfDigit * figure + lowerOfDigit + 1; } else { count += (higherOfDigit+1) * figure; } figure = figure * 10; //数字左移一位 } return count; } void main() { int Digit; int max=0; while((cout<<" 需要结束测试请输入0\n请输入要测试的数值(tip:输入自然数):"<<endl)&&(cin>>Digit)) { if(Digit == 0) break; cout<<"从数字1到数字"<<Digit<<"包含1个数为:"<<Count1Num(Digit)<<endl; } }
四.截图
五.总结
课堂练习:给定一个十进制的正整数,写下从1开始,到N的所有整数,然后数一下其中出现“1”的个数。
标签:
原文地址:http://www.cnblogs.com/littilsaber/p/4472895.html