统计位数

统计位数

统计n以内的正整数一共有多少位数字,不统计前导0.

Exp: n=13,输出17,即1 2 3 4 5 6 7 8 9 10 11 12 13

#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;
long long Tongji(long long num){
	long long x = num;
	long long count = 0;
	int wei = 0;
	while (num){
		wei++;
		num = num / 10;
	}
	long long a = 1;
	for (int i = 1; i <= wei; i++){
		if (i == wei){
			long long temp = a*(x - pow(10, i - 1) + 1);
			count += temp;
		}
		else{
			count = count + 9 * (pow(10, i - 1))*a;
			a++;
		}
	}
	return count;
}

int main(){
	int n;
	long long num;
	cin >> n;
	for (int i = 0; i < n; i++){
		cin >> num;
		cout << Tongji(num) << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/heart_leader/article/details/80024404