1. 程式人生 > >五十道程式設計小題目 --- 24 java

五十道程式設計小題目 --- 24 java

【程式24】 
題目:給一個不多於5位的正整數,要求:一、求它是幾位數,二、逆序打印出各位數字。 

import java.util.Collections;
import java.util.LinkedList;
import java.util.Scanner;

public class Test24 {
	
	public static void test24(){
		
		System.out.println("請輸入小於等於五位的數:");
		Scanner s = new Scanner(System.in);
		int n = s.nextInt();
		System.out.println("輸入數為:" + n);
		
		if(n>99999){
			System.out.println("請輸入小於等於五位的數:");
			System.exit(0);
		}
		
		int m = n;  //一會用作倒序列印
		
		int count = 1 ;    //統計幾位 
		while(n/10 > 0){
			n = n/10;
			count++;
		}
		System.out.println("該數為" + count + "位數");
		
		LinkedList<Integer> list = new LinkedList<>();
		
		for(int i=0; i<count;i++){
			list.add(m%10);   
			m = m/10;
		}
		
		//列印翻轉後的數
		String str = "";
		for(int i=0; i<count;i++){
			str += list.get(i);
		}
		
		System.out.println("翻轉後數為:" + str.toString());
		
		s.close();
	}
	
	public static void main(String[] args) {
		
		test24();
	}

}

輸出結果:
請輸入小於等於五位的數:
9746
輸入數為:9746
該數為4位數
翻轉後數為:6479