Leetcode 738. Monotone Increasing Digits(算法分析week16)

来源:互联网 发布:手机点歌台软件 编辑:程序博客网 时间:2024/05/16 12:50

Monotone Increasing Digits

-问题描述-
-算法分析-
-代码实现-

问题描述

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].

算法分析

问题大意:对于给定数字N,找出小于等于N的一个数result,result满足 result中任意相邻数字x,y, x<=y。
大致算法:
1、将数字N每位数字用数组a存储起来,其中N的最低位为a[0]。
2、从数字N的最高位第s位开始进行判断,如果a[i] > a[i-1],则a[i] = a[i] - 1,a[i-1]~a[0]的值均为9;否则,a[i]值不变。
3、重做步骤二直到数组a中全部相邻元素满足a[i] < a[i+1]。
4、最后得到的数组a 的元素就是result的每位数字,其中a[0]表示最低位数字。

代码实现

@requires_authorizationclass Solution {public:    int monotoneIncreasingDigits(int N) {    int a[100];    int t = N;    int flag = 10;    int i = -1;    while (t != 0) {        i++;        a[i] = t%flag;        t = t / 10;    }    int s = i;    int flag1 = 0;    while (flag1 == 0) {        i = s;        int j = 0;        for (j = s; j > 0; j--) {            if (a[j] > a[j - 1])                break;        }        if (j == 0) flag1 = 1;        while (i != 0) {            if (a[i] > a[i - 1]) {                a[i] = a[i] - 1;                for (i; i > 0; i--) {                    a[i - 1] = 9;                }            }            else {                i--;            }        }    }    flag = 1;    int sum = 0;    for (int i = 0; i <= s; i++) {        sum += a[i] * flag;        flag *= 10;    }    return sum;}};