现在的位置: 首页 > 综合 > 正文

输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。

2013年10月23日 ⁄ 综合 ⁄ 共 514字 ⁄ 字号 评论关闭

import java.util.Scanner;

//题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。

//例如输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。

public class CiShu {

 public static void main(String args[]) {

  Scanner cin = new Scanner(System.in);
  int a = cin.nextInt();

  int result = 0;
  for (int i = 1; i <= a; i++) {
   result = result + contains1num(i);

  }
  System.out.print(result);
 }

 private static int contains1num(int num) {
  int count = 0;

  for (int i = 0; i < 6; i++)// 统计的位数
  {
   if (num % Math.pow(10, i + 1) == Math.pow(10, i))
    count++;
   num = (int) (num - num % Math.pow(10, i + 1));

  }

  return count;

 }

}

抱歉!评论已关闭.