題目:給一個不多於5位的正整數, – JAVA編程語言程序開發技術文章

//請大傢多多指教;
[java]
import java.util.Scanner; 
 
/*題目:給一個不多於5位的正整數,
 * 要求:一、求它是幾位數,二、逆序打印出各位數字。   
*/ 
<span style="BACKGROUND-COLOR: #66ff99">public class Reversed { 
 
    int n = 0; 
     
    public int Digit(int m){ 
        do{ 
            n++; 
        }while(m > Math.pow(10, n)); 
        return (n); 
    } 
     
    public int Output(int m){ 
        int sum = 0; 
        for(int i = 0;i < n;i++){ 
            int temp1 = (int) (m%Math.pow(10, n-i)); 
            int temp2 = (int) (temp1/Math.pow(10, n-i-1)); 
            int temp = (int) (temp2 * Math.pow(10, i)); 
             
            /*System.out.println(i+","+temp1);
            System.out.println(i+","+i+","+temp2);
            System.out.println(i+","+temp);*/ 
            sum += temp; 
        } 
        return sum; 
    } 
     
    public static void main(String[]args){ 
        Reversed r = new Reversed(); 
        System.out.println("請輸入一個整數:"); 
        Scanner in = new Scanner(System.in); 
        int x = in.nextInt(); 
         
        System.out.println(x+"是一個"+r.Digit(x)+"位數"); 
        System.out.println(x+"逆序輸出的結果是:"+r.Output(x)); 
    } 

</span> 

摘自 djw10962000的專欄

發佈留言