[leetcode]贪心算法之Monotone Increasing Digits
贪心算法之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.)
Ex1:
Input: N = 10
Output: 9
Ex2:
Input: N = 1234
Output: 1234
Ex3:
Input: N = 332
Output: 299
答案
class Solution {
public:
int monotoneIncreasingDigits(int N) {
string s="";
while(N){
s.push_back('0'+N%10);
N/=10;
}
reverse(s.begin(),s.end());
int size=s.size();
for(int i=size-2;i>=0;i--){
if(s[i]>s[i+1]){
s[i]=s[i]-1;
for(int j=i+1;j<size;j++){
s[j]='9';
}
}
}
return stoi(s);
}
};
反思
monotone Increasing的意思是单调上升,是不严格,意思是<=
因此从最后一位比较,逐渐降低位数,当降低位数后,后面的位数都可以填充’9’
解题过程中遇到的坑: 要把字符串而不是整数push_back到字符串里
学习了函数
stoi() 和 reverse()的用法
复习字符串和数字相互转换的方法:
数字->字符串
- sprintf
- stringstream
- itoa
- itos
字符串转数字:
- stringstream
- atoi
- stoi
还没有评论,来说两句吧...