2014-11-04 94 views
-1

好吧,所以我有一個練習,我需要找到一個數字中的最高和最低的數字,並將它們加在一起。因此,我有一個數字n是5368,代碼需要找到最高(8)和最低(3)號並添加在一起(11)。怎麼做呢我已經試過這樣的事情:?如何找到多位數字中的最高位?

public class Class { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     int n1 = 5; 
     int n2 = 3; 
     int n3 = 6; 
     int n4 = 8; 
     int max = Math.max(n2 ,n4); 
     int min = Math.min(n2, n4); 
     int sum = max + min; 

     System.out.println(sum); 
    } 

} 

這有點兒工作,但我有一個4位數字,這裏和Math.max /分鐘我只能使用2個參數。我該如何做?提前致謝。

+0

可能重複:最大/最小一個數組中的值?](http://stackoverflow.com/questions/1484347/java-max-min-value-in-an-array) – jruizaranguren 2014-11-04 16:03:44

+1

一個解決方案:使用'String.valueOf(int)'來轉換你的數字到一個'String',得到它的'char []',對它進行排序,得到第一個和最後一個索引。要提取每個字符的值,只需使用'c''0'。而已! – 2014-11-04 16:07:25

回答

2

我認爲其目的是從n = 5368做,所以你需要一個循環拉每一個人數位,並將其與當前的最小值/最大值[Java的

int n = 5368; 
int result = 0; 

if (n > 0) { 
    int min = Integer.MAX_VALUE; 
    int max = Integer.MIN_VALUE; 

    while (n > 0) { 
     int digit = n % 10; 

     max = Math.max(max, digit); 
     min = Math.min(min, digit); 

     n /= 10; 
    } 

    result = min + max; 
} 

System.out.println(result); 
+0

謝謝你,那正是我需要的:D – Oktavix 2014-11-04 19:06:28

相關問題