当前位置:网站首页>力扣: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);
}
};
边栏推荐
- svn安装及使用(身体功能手册)
- Resnet&API
- 常用工具命令速查表
- 安装Xshell并使用其进行Ymodem协议的串口传输
- Description of Hikvision camera streaming RTSP address rules
- OpenShift 4 - 用 Operator 部署 Redis 集群
- Shell script classic case: backup of files
- Uniapp WeChat small application reference standard components
- The role of /etc/profile, /etc/bashrc, ~/.bash_profile, ~/.bashrc files
- How to grab configuration information for DELL SC compellent storage system
猜你喜欢

OAuth2:资源服务器

Spark学习(2)-Spark环境搭建-Local

Essential Learning for Getting Started with Unity Shader - Transparency Effect

Combination series - there are combinations when there are arrangements

NC | 斯坦福申小涛等开发数据可重复分析计算框架TidyMass

公告

sentinel与nacos持久化

Redis 】 【 publish and subscribe message

Getting started with UnityShader (1) - GPU and Shader

Redis与分布式:哨兵模式
随机推荐
NPM Taobao mirror (latest version) released a new version of npm mirror at 2021-11-21 16:53:52 [easy to understand]
The use of thread pool two
Open Inventor 10.12 Major Improvements - Harmony Edition
纸质说明书秒变3D动画,斯坦福大学吴佳俊最新研究,入选ECCV 2022
OAuth2:四种授权方式
Introduction to BigDecimal, common methods
最近很火的国产接口神器Apipost体验
架构实战营模块8消息队列表结构设计
Getting started with UnityShader (1) - GPU and Shader
Motion capture system for end-positioning control of flexible manipulators
MySQL [aggregate function]
Selenium自动化中无头浏览器的应用
OAuth2:资源服务器
学习笔记12--路径-速度分解法之局部路径搜索
OAuth2:搭建授权服务器
Groupid(artifact id)
Advanced Mathematics - Commonly Used Indefinite Integral Formulas
leetcode: 485. Maximum number of consecutive 1s
五个维度着手MySQL的优化
1小时直播招募令:行业大咖干货分享,企业报名开启丨量子位·视点