2017-09-03 72 views
1

我試圖用1個輸入來獲得發生最大數量的計數。獲取發生次數的最大值

我的代碼如下所示: -

Scanner input = new Scanner(System.in); 
    int num = input.nextInt(); 
    int max = 0, count = 0, value, lastValue = 0; 

    while (num > 0){ 

     value = num % 10; 
     num = num/10; 
     if (value > lastValue){ 
      max = value; 
     } 

     lastValue = value; 
    } 

    System.out.println(max); 
    System.out.println("count is " + count); 
} 

我怎麼能計算出最大號的數量?

假設我有類似於2556621的輸入count應該是2

+0

在什麼時候是你卡住? – pedromss

+0

@pedromss自從我使用1個輸入項後,獲得最大數量的計數,使用多個輸入項很容易,但在我的情況下,我可以如何實現這一點。 ? – user1058652

+0

爲什麼你使用一個輸入呢? –

回答

1

它看起來像你的代碼應該是

Scanner input = new Scanner(System.in); 
    int num = input.nextInt(); 
    int max = 0, count = 0, value = 0; 

    while (num > 0){ 

     value = num % 10; 
     num = num/10; 
     if (value > max){ 
      max = value; 
      count = 1; 
     } else if (value == max){ 
      count++; 
     } 
    } 

    System.out.println(max); // 6 for 2556621 
    System.out.println("count is " + count); // 2 for 2556621 
} 
+0

是的,這是真的,謝謝你的時間,我明白這一點。 – user1058652