首页 > 试题广场 >

1到n中1的出现次数

[编程题]1到n中1的出现次数
  • 热度指数:1738 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个整数n,返回从1到n的数字中1出现的个数。
例如:
那么1出现了1次,所以返回1。
那么1出现的次数为1(出现1次),10(出现1次),11(有两个1,所以出现了2次),所以返回4。

输入描述:
输入一个整数N。


输出描述:
输出一个整数表示答案
示例1

输入

5

输出

1
示例2

输入

11

输出

4
示例3

输入

2345

输出

1775

备注:
https://blog.csdn.net/yi_Afly/article/details/52012593?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1 这篇博客讲的很清楚,然后要注意10的13次超出了int的表示范围

import java.util.Scanner;

/*
 *
 * https://www.nowcoder.com/practice/38af9b5a06ea4448ae9b2a488b6a991f?tpId=101&&tqId=33140&rp=1&ru=/activity/oj&qru=/ta/programmer-code-interview-guide/question-ranking
 *
 * */
public class Main {
    public static long count(long n) {
        if (n < 1) {
            return 0;
        }
        long count = 0;
        long round = n;
        long weight = 0;
        long base = 1;
        while (round > 0) {
            weight = round % 10;
            round = round / 10;
            count += round * base;
            if (weight == 1) {
                count += n % base + 1;
            } else if (weight > 1) {
                count += base;
            }
            base *=10;
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        System.out.println(count(n));
    }
}

发表于 2020-04-09 23:04:10 回复(0)