当前位置:网站首页>力扣:738.单调递增的数字
力扣:738.单调递增的数字
2022-07-31 14:46:00 【empty__barrel】
力扣:738.单调递增的数字
题目:
给定一个非负整数 N,找出小于或等于 N 的最大的整数,同时这个整数需要满足其各个位数上的数字是单调递增。
(当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。)
思路很简单,不述
原代码超时:
class Solution {
public:
int monotoneIncreasingDigits(int n) {
if (n < 10) return n;
vector<int>v;
while (n > 0) {
//直接使用数字转换成字符串的函数,简便快捷 to_string(N)
v.push_back(n % 10);
n /= 10;
}
int next = -1; //没有必要使用now,和next来记录当前元素和下一个元素,浪费空间
int now = -1;
int point = -1;
for (int i = 0; i < v.size(); ++i) {
if (v[i] > v[i-1] && v[i-1] != -1) {
v[i] = v[i] - 1;
point = i - 1;
}
if (i = v.size() - 1 && point != -1) {
//这个表达式还会判断n回,浪费时间,下面的for直接放在for循环外面直接操作
for (int j = point; j > -1; --j) {
v[j] = 9;
}
}
}
int result = 0;
for (int i = v.size() - 1; i >= 0; --i) {
result *= 10;
result += v[i];
}
return result;
}
};
简便快捷代码:
class Solution {
public:
int monotoneIncreasingDigits(int N) {
string strNum = to_string(N);
// flag用来标记赋值9从哪里开始
// 设置为这个默认值,为了防止第二个for循环在flag没有被赋值的情况下执行
int flag = strNum.size();
for (int i = strNum.size() - 1; i > 0; i--) {
if (strNum[i - 1] > strNum[i] ) {
flag = i;
strNum[i - 1]--;
}
}
for (int i = flag; i < strNum.size(); i++) {
strNum[i] = '9';
}
return stoi(strNum);
}
};
边栏推荐
- OpenShift 4 - Customize RHACS security policies to prevent production clusters from using high-risk registry
- [QNX Hypervisor 2.2用户手册]9.14 safety
- TCP详解
- C language basic practice (nine-nine multiplication table) and printing different asterisk patterns
- 我把问烂了的MySQL面试题总结了一下
- OpenCV测量物体的尺寸技能 get~
- OAuth2:使用JWT令牌
- Groupid(artifact id)
- NC | 斯坦福申小涛等开发数据可重复分析计算框架TidyMass
- el-tooltip的使用
猜你喜欢
随机推荐
Comparison of Optical Motion Capture and UWB Positioning Technology in Multi-agent Cooperative Control Research
Advanced Mathematics - Commonly Used Indefinite Integral Formulas
自适应控制——仿真实验三 用超稳定性理论设计模型参考自适应系统
Linux bash: redis-server: command not found
Small test knife: Go reflection helped me convert Excel to Struct
MySQL【聚合函数】
UnityShader入门学习(二)——渲染流水线
小试牛刀:Go 反射帮我把 Excel 转成 Struct
I summed up the bad MySQL interview questions
Node实现数据加密
[QNX Hypervisor 2.2 User Manual]9.14 safety
Essential Learning for Getting Started with Unity Shader - Transparency Effect
NC | 斯坦福申小涛等开发数据可重复分析计算框架TidyMass
Shell script classic case: detecting whether a batch of hosts is alive
OAuth2:搭建授权服务器
Message queue data storage MySQL table design
jvm 一之 类加载器
OpenShift 4 - Customize RHACS security policies to prevent production clusters from using high-risk registry
ERROR: Failed building wheel for osgeo
梅克尔工作室-第一次