你前边有多少个一?

题目要求
给定一个十进制的正整数,记录从1开始,到N的所有整数,然后数一下其中出现“1”的个数。
写一个函数 f(N) ,返回1 到 N 之间出现的“1”的个数。例如 f(12)  = 4。
实验思路
从个位开始考虑,个位上若不为0,则有一的个数为n/10+1,否则为n/10;
十位上若不为0,则有一的个数为(n/100+1)*10,否则为n/100;
百位上若不为0,则有一的个数为为(n/1000+1)*100,否则为n/1000;
考虑若最高位上为一,则最高位有一的个数为n去掉最高位的一;
实验代码
package 多少个一;

import java.util.Scanner;

public class aa {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int a,b,l;
        int i;
        double m;
        Scanner scanner = new Scanner(System.in);
        //System.out.print("请输入一个数:");
        //a=scanner.nextInt();
        scanner.close();
        
        for(a=1;a<=100;a++)
        {
            l=1;
            b=a;
            while(b/10!=0)
            {
                l++;
                b/=10;
            }
            b=a;
            int[] c = new int[l+1];
            int[] d = new int[l+1];
            c[0]=0;d[0]=a;
            for(i=1;i<=l;i++)
            {
                c[i]=b%10;
                d[i]=d[i-1]/10;
                b/=10;
            }
            m=0;
            for(i=1;i<=l-1;i++)
            {
                if(c[i]>=1)
                    m=m+(d[i]+1)*Math.pow(10,i-1);
                else
                    m=m+(d[i])*Math.pow(10,i-1);
            }
            if(c[l]>1)
                m=m+(d[i]+1)*Math.pow(10,i-1);
            else if(c[l]==1)
                m=m+a%Math.pow(10,i-1);
            System.out.print(a);
            System.out.print("前边共有");
            System.out.print(m);
            System.out.print("个1.  ");
            if(a%10==0)
                System.out.println();
        }
        
        
    }

}

实验截图

 
原文地址:https://www.cnblogs.com/feifeishi/p/4553722.html