【题目】求出1~n的整数中1出现的次数.(10进制)
1 package com.exe11.offer; 2 /** 3 * 【题目】求出1~n的整数中1出现的次数. 4 * @author WGS 5 * 6 */ 7 public class NumberOf1 { 8 9 public int getNumberOf1Between1AndN(int n){ 10 if(n<=0) return 0; 11 if(n<=9) return 1; 12 int count=0; 13 for(int i=1;i<=n;i++){ 14 count+=getCount(i); 15 } 16 return count; 17 18 } 19 private int getCount(int n) { 20 int numberOf1=0; 21 int flag=0; 22 while(n!=0){ 23 flag=n%10; 24 if(flag==1) 25 numberOf1++; 26 n=n/10; 27 } 28 return numberOf1; 29 } 30 public static void main(String[] args) { 31 NumberOf1 n=new NumberOf1(); 32 int num=n.getNumberOf1Between1AndN(7); 33 System.out.println(num); 34 35 } 36 37 }
时间: 2024-10-06 21:44:41