Skip to content

Latest commit

 

History

History
executable file
·
65 lines (49 loc) · 1.82 KB

编程练习-1的数目.md

File metadata and controls

executable file
·
65 lines (49 loc) · 1.82 KB

题目: 1的数目

  • 来源: 编程之美 给定一个十进制正整数N,写下从1开始,到N的所有整数,然后数一下其中出现的所有"1"的个数。 例如:

N = 2,写下1,2。这样只出现了1个"1" N = 12, 1,2,3,4,5,6,7,8,9,10,11,12。这样1的个数为5;

分析

具体分析见图

实现


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            System.out.println(Sum1s(Long.parseLong(scanner.next())));
        }

    }

    public static long Sum1s(long n) {

        long iCount = 0;    //
        long iFactor = 1;   // 个十百千万
        long iLowerNum = 0; // 低位数字 比如12123,以百位1为界,低位数字为23
        int iCurrNum = 0;   // 每一位上的数字,取值0-9
        long iHigherNum = 0;    // 高位数字,类似上面

        while (n / iFactor != 0) {

            iLowerNum = n - (n / iFactor) * iFactor;    // 获得高位数字
            iCurrNum = (int)(n / iFactor) % 10; // 获得当前位数字
            iHigherNum = n / (iFactor * 10);    // 获得高位数字

            switch (iCurrNum) {
                case 0 :
                    iCount += iHigherNum * iFactor; // 高位 * 当前位数
                    break;
                case 1:
                    iCount += iHigherNum * iFactor + iLowerNum +1;  //
                    break;
                default:
                    iCount += (iHigherNum + 1) * iFactor;
                    break;
            }

            iFactor *= 10;
        }

        return iCount;
    }

}

此致,敬礼