738:单调递增的数字

This commit is contained in:
huangge1199@hotmail.com 2021-09-08 21:52:50 +08:00
parent 6aee12ffeb
commit 7792a21b38
3 changed files with 84 additions and 1 deletions

View File

@ -0,0 +1,59 @@
//给定一个非负整数 N找出小于或等于 N 的最大的整数同时这个整数需要满足其各个位数上的数字是单调递增
//
// 当且仅当每个相邻位数上的数字 x y 满足 x <= y 我们称这个整数是单调递增的
//
// 示例 1:
//
// 输入: N = 10
//输出: 9
//
//
// 示例 2:
//
// 输入: N = 1234
//输出: 1234
//
//
// 示例 3:
//
// 输入: N = 332
//输出: 299
//
//
// 说明: N 是在 [0, 10^9] 范围内的一个整数
// Related Topics 贪心 数学 👍 205 👎 0
package leetcode.editor.cn;
//738:单调递增的数字
class MonotoneIncreasingDigits {
public static void main(String[] args) {
//测试代码
Solution solution = new MonotoneIncreasingDigits().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int monotoneIncreasingDigits(int n) {
char[] arr = (n + "").toCharArray();
int max = -1, idx = -1;
for (int i = 0; i < arr.length - 1; i++) {
if (max < arr[i]) {
max = arr[i];
idx = i;
}
if (arr[i] > arr[i + 1]) {
arr[idx] -= 1;
for (int j = idx + 1; j < arr.length; j++) {
arr[j] = '9';
}
break;
}
}
return Integer.parseInt(new String(arr));
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,24 @@
<p>给定一个非负整数&nbsp;<code>N</code>,找出小于或等于&nbsp;<code>N</code>&nbsp;的最大的整数,同时这个整数需要满足其各个位数上的数字是单调递增。</p>
<p>(当且仅当每个相邻位数上的数字&nbsp;<code>x</code>&nbsp;&nbsp;<code>y</code>&nbsp;满足&nbsp;<code>x &lt;= y</code>&nbsp;时,我们称这个整数是单调递增的。)</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> N = 10
<strong>输出:</strong> 9
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> N = 1234
<strong>输出:</strong> 1234
</pre>
<p><strong>示例 3:</strong></p>
<pre><strong>输入:</strong> N = 332
<strong>输出:</strong> 299
</pre>
<p><strong>说明:</strong> <code>N</code>&nbsp;是在&nbsp;<code>[0, 10^9]</code>&nbsp;范围内的一个整数。</p>
<div><div>Related Topics</div><div><li>贪心</li><li>数学</li></div></div><br><div><li>👍 205</li><li>👎 0</li></div>