【Leetcode】 738. 单调递增的数字

当且仅当每个相邻位数上的数字 xy 满足 x <= y 时,我们称这个整数是单调递增的。

给定一个整数 n ,返回 小于或等于 n 的最大数字,且数字呈 单调递增

示例 1:

输入: n = 10
输出: 9

示例 2:

输入: n = 1234
输出: 1234

示例3 :

输入: n = 332
输出: 299

提示:

0 <= n <= 109

AC:

/*
 * @lc app=leetcode.cn id=738 lang=cpp
 *
 * [738] 单调递增的数字
 */

// @lc code=start
class Solution {
public:
    int monotoneIncreasingDigits(int n) {
        string str = to_string(n);
        int flag = str.size();
        for(int i = str.size() - 1; i > 0; i--) {
            if(str[i - 1] > str[i]) {
                str[i - 1]--;
                flag = i;
            }
        }
        for(int i = flag; i < str.size(); i++) {
            str[i] = '9';
        }
        return stoi(str);
    }
};
// @lc code=end

【Leetcode】 738. 单调递增的数字_第1张图片

需要注意的点:整数型转字符串操作以及字符串转整数操作


  • C++11引入了std::to_string函数,可以将数字类型转换为字符串类型。使用方法如下:
#include 
#include 

int main() {
    int i = 123;
    std::string s = std::to_string(i);
    std::cout << s << std::endl;
    return 0;
}

输出结果为:

123

底层逻辑:

  • 在实现上,std::to_string调用了std::stringstream,将数值类型转换为字符串类型。可以理解为它是一个基于流的解决方案,也可以通过以下方式手动转换:
#include 
#include 
#include 

int main() {
    int i = 123;
    std::stringstream ss;
    ss << i;
    std::string s = ss.str();
    std::cout << s << std::endl;
    return 0;
}

输出结果与上例相同。


  • C++11引入了std::stoi函数,可以将字符串转换为整型。使用方法如下:
#include 
#include 

int main() {
    std::string s = "123";
    int i = std::stoi(s);
    std::cout << i << std::endl;
    return 0;
}

输出结果为:

123

如果字符串无法转换为整型,则会抛出std::invalid_argumentstd::out_of_range两种异常。例如:

#include 
#include 

int main() {
    std::string s = "abc";
    try {
        int i = std::stoi(s);
        std::cout << i << std::endl;
    }
    catch (const std::invalid_argument& ia) {
        std::cerr << "Invalid argument: " << ia.what() << std::endl;
    }
    catch (const std::out_of_range& oor) {
        std::cerr << "Out of range: " << oor.what() << std::endl;
    }
    return 0;
}

输出结果为:

Invalid argument: stoi

底层逻辑:

  • 在实现上,std::stoi使用了std::strtol函数,将字符串转换为长整型,然后进行类型转换。它还使用了std::locale,允许指定特定的本地化设置来解析字符串。可以理解为它是一个更简单的基于C函数的解决方案,也可以通过以下方式手动转换:
#include 
#include 
#include 

int main() {
    std::string s = "123";
    char* end;
    int i = std::strtol(s.c_str(), &end, 10);
    if (*end == '\0') {
        std::cout << i << std::endl;
    }
    else {
        std::cerr << "Invalid argument" << std::endl;
    }
    return 0;
}

输出结果与上例相同。

你可能感兴趣的:(Leetcode,leetcode,算法,职场和发展)