您的位置:首页 > 其它

(CareerCup)Find next higher number with same digits

2014-04-03 12:50 281 查看
题目地址:http://www.careercup.com/question?id=4869907900530688

Find next higher number with same digits.
Example 1 : if num = 25468, o/p = 25486
Example 2 : if num = 21765, o/p = 25167
Example 3 : If num = 54321, o/p = 54321 (cause it's not possible to gen a higher num than tiz with given digits ).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FindNextHigherNumberWithSameDigits
{
class Program
{
static void Main(string[] args)
{
Do();
}

static void Do()
{
Console.WriteLine("plz input number: ");
int input = Convert.ToInt32(Console.ReadLine());
var arrayInput = input.ToString().ToCharArray();
Find(ref arrayInput);
Console.WriteLine("result : " + string.Join("", arrayInput));
Do();
}

static void Find(ref char[] array)
{
int indexFirst = 0;
int indexLast = array.Length - 1;
bool hasChanged = false;
for (int i = array.Length - 1; i > 0; i--)
{
//find the number larger than before one
if (array[i] > array[i - 1])
{
hasChanged = true;
indexLast = i;
indexFirst = i - 1;
//find the number smaller than the number we found
//and larger than the previous number of the number we found
for (int a = array.Length - 1; a >= i; a--)
{

if (array[a] > array[i - 1] && array[a] < array[i] && array[a] <= array[indexLast])
{
indexLast = a;
indexFirst = i - 1;
}
}
break;
}
}
//if the number is descending, return .
if (!hasChanged) return;

var temp = array[indexFirst];
array[indexFirst] = array[indexLast];
array[indexLast] = temp;
//sort the number after previous position
Array.Sort(array, indexFirst + 1, array.Length - indexFirst - 1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: