1、計算數字位數java
一、題目python
給定一個數字T,計算從1到T的全部正整數的位數和。好比T=13,則12345678910111213有17位數字。blog
輸入描述it
3class
13 4 5import
輸出im
17 4 5next
二、思路數據
詳見代碼部分static
三、代碼
import java.util.Scanner; /** * Created by Administrator on 2018/4/20. */ public class Main1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { //輸入數據組數 int T = sc.nextInt(); //輸入數據 int[] arr = new int[T]; for (int i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } //計算 int result ; for (int i = 0; i < arr.length; i++) { result = bitNum(arr[i]); System.out.println(result); } } sc.close(); } public static int bitNum(int n) { //計算n的位數 int num = n; int count = 0; while (n > 0) { n = n / 10; count++; } //若是爲1位數 if (count == 1) { return num; } //若是不是1位數,計算總的位數 int num1 = 0; //總位數的一部分 for (int i = 0; i < count-1; i++) { num1 += 9 * Math.pow(10, i) * (i + 1); } int temp1 = (int) (num % Math.pow(10,count-1));//去掉最高位剩下的數 int temp2 = (int) (num / Math.pow(10,count-1)); //數的最高位 int num2 = (int) ((temp1 + 1) * count + (temp2 - 1) * Math.pow(10,count-1) * count); //總位數的另外一部分 return num1 + num2; } }
-------------------------------------------
答案僅供參考