Leetcode 738. Monotone Increasing Digits
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 738. Monotone Increasing Digits
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原題鏈接:https://leetcode.com/problems/monotone-increasing-digits/description/
描述:
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.
(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)
Example 1:
Input: N = 10
Output: 9
Example 2:
Input: N = 1234
Output: 1234
Example 3:
Input: N = 332
Output: 299
Note: N is an integer in the range [0, 10^9].
Solution:
本題依然是數學問題,只需要找出需要調整的數即可,然后其后面的數全部賦9即可保證最大,分幾種情況討論,從位數低的開始考慮,需要找出的是最后一次從右向左出現遞增的位置,然后中間需要加上數字重復的情況,如果數字重復剛好出現在遞增的位置,那么也同樣移動標記位,但如果沒有移動過標記位,則將原數輸出,具體代碼如下所示:
#include <iostream> #include <cmath> using namespace std;int monotoneIncreasingDigits(int N) {int i = 0; // 記錄需要調整的位置int j = 0; // 位數bool flag = 0; // 標記是否是轉折點int n = N;int m1 = n % 10; // 末位數n = n / 10;while (n) {j++;int m2 = n % 10;// 倒數第二個數if (m1 < m2) {flag = 1;i = j;} else {if (flag && m1 == m2) i = j;else flag = 0;}m1 = m2;n /= 10;}return i == 0 ? N : ((N / int(pow(10, i)) - 1) * pow(10, i) + int(pow(10, i)) - 1); }int main() {int N;while (cin >> N) {cout << monotoneIncreasingDigits(N) << endl;}system("pause");return 0; }總結
以上是生活随笔為你收集整理的Leetcode 738. Monotone Increasing Digits的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OKR的基本介绍
- 下一篇: win10更新后分辨率不可设置、只能设置