Leetcode 738. Monotone Increasing Digits
来源:互联网 发布:手写笔画图软件 编辑:程序博客网 时间:2024/06/05 08:39
原题链接:https://leetcode.com/problems/monotone-increasing-digits/description/
描述:
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].
Solution:
本题依然是数学问题,只需要找出需要调整的数即可,然后其后面的数全部赋9即可保证最大,分几种情况讨论,从位数低的开始考虑,需要找出的是最后一次从右向左出现递增的位置,然后中间需要加上数字重复的情况,如果数字重复刚好出现在递增的位置,那么也同样移动标记位,但如果没有移动过标记位,则将原数输出,具体代码如下所示:
#include <iostream>#include <cmath>using namespace std;int monotoneIncreasingDigits(int N) { int i = 0; // 记录需要调整的位置 int j = 0; // 位数 bool flag = 0; // 标记是否是转折点 int n = N; int m1 = n % 10; // 末位数 n = n / 10; while (n) { j++; int m2 = n % 10;// 倒数第二个数 if (m1 < m2) { flag = 1; i = j; } else { if (flag && m1 == m2) i = j; else flag = 0; } m1 = m2; n /= 10; } return i == 0 ? N : ((N / int(pow(10, i)) - 1) * pow(10, i) + int(pow(10, i)) - 1);}int main() { int N; while (cin >> N) { cout << monotoneIncreasingDigits(N) << endl; } system("pause"); return 0;}
阅读全文
0 0
- Leetcode 738. Monotone Increasing Digits
- LeetCode刷题 | 738. Monotone Increasing Digits
- LeetCode—738. Monotone Increasing Digits
- 738. Monotone Increasing Digits
- 738. Monotone Increasing Digits
- leetcode weekly contest 61 ( 738. Monotone Increasing Digits )
- Leetcode 738. Monotone Increasing Digits(算法分析week16)
- LWC 61:738. Monotone Increasing Digits
- 【算法分析与设计】【第十四周】738. Monotone Increasing Digits
- Monotone Increasing Digits问题及解法
- [LeetCode]Longest Increasing Subsequence
- [LeetCode] Longest Increasing Subsequence
- leetcode-Longest Increasing Subsequence
- [LeetCode]Longest Increasing Subsequence
- *LeetCode-Longest Increasing Subsequence
- Leetcode: Longest Increasing Subsequence
- LeetCode Longest Increasing Subsequence
- LeetCode -- Longest Increasing Subsequence
- org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'shiroFilter' 错误解决办法
- easyui 合并单元格
- java实现自动生成多级目录
- 之前一直在找字典是如何封装的,一直找不到,自己就试着封装了个字典(Dictionary)
- Linux 查看服务器开放的端口号
- Leetcode 738. Monotone Increasing Digits
- 第一次写博客
- 面试编程题5:实现字符串翻转并输出
- test
- Python基础语法-常量与变量
- 日记(6)
- Eclipse常用快捷键
- 【Yoshua Bengio 亲自解答】机器学习 81 个问题及答案(最全收录)
- 简单数据类型之字符串