大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
987 B

  1. /*
  2. n1~n这n个整数的十进制表示中1出现的次数
  3. 1~1311101112136
  4. */
  5. #include <iostream>
  6. using namespace std;
  7. // 函数用于计算从1到n中'1'出现的次数
  8. int countDigitOne(int n){
  9. int count = 0;
  10. long long factor = 1;// 用来表示当前分析的位(个位、十位、百位等)
  11. while(n / factor > 0){
  12. long long lower= n - (n / factor) * factor;// 当前位以下的数字
  13. long long current=(n / factor) % 10;
  14. long long higher=n / (factor * 10);
  15. if(current == 0){
  16. count += higher * factor;
  17. }
  18. else if(current == 1){
  19. count += higher * factor + lower + 1;
  20. }
  21. else {
  22. count +=(higher + 1) * factor;
  23. }
  24. factor *= 10;// 进入到下一位
  25. }
  26. return count;
  27. }
  28. int main(){
  29. int n;
  30. cin >> n;
  31. cout<< countDigitOne(n)<<endl;
  32. return 0;
  33. }