C++程式:查詢給定數字中的最小數字


給定一個非負數,任務是找到其最小數字。

例如

輸入

N = 154870

輸出

0

解釋:在給定的數字“154870”中,最小數字是“0”。

解決此問題的方法

解決此問題的最簡單方法是使用餘數定理提取給定數字的最後一位數字。在遍歷數字時,我們將檢查提取的數字是否小於最後一位數字,然後返回結果。

  • 將數字n作為輸入。
  • 整數函式smallest_digit(int n)將'n'作為輸入,並返回給定數字中的最小數字。
  • 現在將min初始化為給定數字的最後一位數字。
  • 遍歷數字並檢查提取的數字是否小於最小數字。如果為真,則更新最小數字並返回結果。
  • 透過n/10去除最後一位數字,並檢查是否存在另一個數字小於當前數字。
  • 返回結果。

示例

線上演示

#include <iostream>
using namespace std;
int smallest_digit(int n) {
   int min = n % 10; //assume that last digit is the smallest
   n /= 10; //to start from the second last digit
   while (n != 0) {
      if (min > n % 10)
         min = n % 10;
      n /= 10;
   }
   return min;
}
int main() {
   int n = 154870;
   cout << smallest_digit(n);
   return 0;
}

執行上述程式碼將生成以下輸出:

輸出

0

解釋:在給定的數字“154870”中,最小數字是“0”。

更新於:2021年2月23日

3K+瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.