Leetcode 738. Monotone Increasing Digits(算法分析week16)
来源:互联网 发布:手机点歌台软件 编辑:程序博客网 时间:2024/05/16 12:50
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.)
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].
算法分析
问题大意:对于给定数字N,找出小于等于N的一个数result,result满足 result中任意相邻数字x,y, x<=y。
大致算法:
1、将数字N每位数字用数组a存储起来,其中N的最低位为a[0]。
2、从数字N的最高位第s位开始进行判断,如果a[i] > a[i-1],则a[i] = a[i] - 1,a[i-1]~a[0]的值均为9;否则,a[i]值不变。
3、重做步骤二直到数组a中全部相邻元素满足a[i] < a[i+1]。
4、最后得到的数组a 的元素就是result的每位数字,其中a[0]表示最低位数字。
代码实现
@requires_authorizationclass Solution {public: int monotoneIncreasingDigits(int N) { int a[100]; int t = N; int flag = 10; int i = -1; while (t != 0) { i++; a[i] = t%flag; t = t / 10; } int s = i; int flag1 = 0; while (flag1 == 0) { i = s; int j = 0; for (j = s; j > 0; j--) { if (a[j] > a[j - 1]) break; } if (j == 0) flag1 = 1; while (i != 0) { if (a[i] > a[i - 1]) { a[i] = a[i] - 1; for (i; i > 0; i--) { a[i - 1] = 9; } } else { i--; } } } flag = 1; int sum = 0; for (int i = 0; i <= s; i++) { sum += a[i] * flag; flag *= 10; } return sum;}};
阅读全文
0 0
- Leetcode 738. Monotone Increasing Digits(算法分析week16)
- Leetcode 738. Monotone Increasing Digits
- 【算法分析与设计】【第十四周】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 )
- LWC 61:738. Monotone Increasing Digits
- Monotone Increasing Digits问题及解法
- Leetcode Week16
- leetcode week16
- (算法分析Week16)Accounts Merge[Medium]
- (算法分析Week16)132 Pattern[Medium]
- 算法设计Week16 LeetCode Algorithms Problem #322 Coin Change
- 【Leetcode算法】-Add Digits
- LeetCode题解 week16
- 【算法设计作业】week16
- SpringMVC与Struts2区别与比较总结
- 你对百兆SFP光模块了解有多少?_千兆单模光模块_万兆金光模块
- linux下安装zookeeper
- 字符串排序
- Floyd-算法--任意两点间的最短路问题
- Leetcode 738. Monotone Increasing Digits(算法分析week16)
- scala map 映射方法
- Junit 4 Tutorials(Junit 4 教程)
- mvc设计模式和mvc框架的区别
- [Unity基础]导入贴图、模型等资源文件时自动设置参数
- 使用JDBC链接MYSQL数据库
- CodeForces 28 C.Bath Queue(概率DP+组合数学)
- 奇葩圣诞礼物idea合辑
- 关于java对Elasticsearch操作相关帮助类(2.4版本,不使用分词器插件)