2014-05-04 00:10
原题:
Write a function return an integer that satisfies the following conditions: 1) positive integer 2) no repeated digits, eg., 123 (valid), 122 (invalid) 3) incremental digit sequence, eg., 1234 (valid) 1243(invalid) 4) the returned integer MUST be the smallest one that greater than the input. eg., input=987, return=1023 function signature could be like this: String nextInteger(String input)
题目:请设计一个函数nextInteger(),以字符串形式的整数为输入,返回一个字符串形式的整数。要去这个整数:1. 是正整数 2. 任何数位的数字不能相同 3. 各个数位由高到低必须严格递增 4. 输出的数字必须是满足上述三条件并且比输入数大的最小的数。其实用英语描述,一个“next”就表达这个意思了。
解法:分析这三个条件,可以很快发现满足条件的数是很少的。各个位的数不能重复,并且还得保持升序,这样的话可以数位动态规划的思想找出所有的数,并进行排序。对于得到的所有符合条件的数组成的数组,进行upper_bound二分查找就能得到题目要求的数了。
代码:
1 // http://www.careercup.com/question?id=4857362737266688 2 #include <algorithm> 3 #include <queue> 4 #include <sstream> 5 #include <string> 6 #include <vector> 7 using namespace std; 8 9 class Solution { 10 public: 11 Solution() { 12 generateNumbers(); 13 }; 14 15 string nextInteger(string input) { 16 int n1, n2; 17 vector<int>::iterator it; 18 stringstream ss; 19 20 ss << input; 21 ss >> n1; 22 it = upper_bound(arr.begin(), arr.end(), n1); 23 if (it == arr.end()) { 24 n2 = n1; 25 } else { 26 n2 = *it; 27 } 28 29 string output = to_string(n2); 30 31 return output; 32 }; 33 private: 34 vector<int> arr; 35 36 void generateNumbers() { 37 queue<int> q; 38 int n, n1; 39 int i, d; 40 41 arr.push_back(0); 42 q.push(0); 43 while (!q.empty()) { 44 n = q.front(); 45 q.pop(); 46 d = n % 10; 47 for (i = d + 1; i <= 9; ++i) { 48 n1 = n * 10 + i; 49 arr.push_back(n1); 50 q.push(n1); 51 } 52 } 53 }; 54 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)