Given a number n, find the smallest number that has same set of digits as n and is greater than n. If x is the greatest possible number with its set of digits, then print “not possible”.
examples:
input: 1111
output: not possible
inout: 1234
output: 1243
input: 12345765
output: 12346557
Solution:
Assume the input is a int[] num.
1. Scan from the end, and find the 1st position i, where num[i] < num[i+1]. Let i be smallPos.
2. Scan from the end again, find the 1st position j, where num[smallPos] < num[j]. Let j be largePos.
3. Do exchange between num[smallPos] and num[largePos].
4. Do exchange from num[smallPos+1] and num[num.length – 1], num[smallPos+2] and num[num.length – 2], num[smallPos+3] and num[num.length – 3] and so on.
This time, I used node.js to solve this problem.
The visiting format is http://allenlipeng47.com:3000/nge/{input}
For example: http://allenlipeng47.com:3000/nge/66355331
There are 2 files: app.js and npe.js:
node/app.js
node/mymodule/npe.js
npe.js:
- /*
- Given a number n, find the smallest number that has same set of digits as n and is greater than n. If x is the greatest possible number with its set of digits, then print “not possible”.
- The input num is a char array type.
- */
- function npe(num){
- num = num.split(”);
- if(num.length==1){
- return ‘not possible’;
- }
- var smallPos = num.length – 2;
- while(smallPos >=0 && num[smallPos] >= num[smallPos+1]){
- smallPos–;
- }
- if(smallPos < 0){
- return ‘not possible’;
- }
- var largePos = num.length – 1;
- while(num[largePos] <= num[smallPos]){
- largePos–;
- }
- var tmp = num[smallPos];
- num[smallPos] = num[largePos];
- num[largePos] = tmp;
- for(largePos = num.length – 1, ++smallPos; smallPos < largePos; smallPos++, largePos–){
- var tmp = num[smallPos];
- num[smallPos] = num[largePos];
- num[largePos] = tmp;
- }
- num = num.join(”);
- return num;
- }
- module.exports = npe;
app.js
- var express = require(‘express’)
- var app = express();
- app.get(‘/nge/:id’, function (req, res){
- var npe = require(‘./mymodule/npe.js’);
- var result = npe(req.params.id);
- res.send(result);
- })
- app.get(‘*’, function (req, res){
- res.send(‘Welcome to Li Peng\’s node.js!’);
- })
- var server = app.listen(3000, function(){
- var host = server.address().address
- var port = server.address().port
- });