mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-09 11:09:07 +01:00
65 lines
1.5 KiB
C#
65 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
public class Kata {
|
|
public static List<long> ExtractDigits(long n) {
|
|
var result = new List<long>();
|
|
|
|
while (n > 0) {
|
|
result.Add(n % 10);
|
|
n /= 10;
|
|
}
|
|
|
|
result.Reverse();
|
|
return result;
|
|
}
|
|
|
|
public static bool NextPermutation(List<long> digits) {
|
|
// foreach (var digit in digits) Console.Write($"{digit} ");
|
|
// Console.WriteLine();
|
|
|
|
var k = -1;
|
|
|
|
for (var i = 0; i < digits.Count - 1; i++) {
|
|
if (digits[i] < digits[i + 1])
|
|
k = i;
|
|
}
|
|
if (k == -1) return false;
|
|
|
|
var l = k;
|
|
for (var i = 0; i < digits.Count; i++)
|
|
if (digits[k] < digits[i]) l = i;
|
|
if (l == k) return false;
|
|
|
|
var tmp = digits[k];
|
|
digits[k] = digits[l];
|
|
digits[l] = tmp;
|
|
|
|
// foreach (var digit in digits) Console.Write($"{digit} ");
|
|
// Console.WriteLine();
|
|
|
|
digits.Reverse(k + 1, digits.Count - k - 1);
|
|
|
|
// foreach (var digit in digits) Console.Write($"{digit} ");
|
|
// Console.WriteLine();
|
|
|
|
return true;
|
|
}
|
|
|
|
public static long NextBiggerNumber(long n) {
|
|
if (n < 10) return -1;
|
|
|
|
var digits = ExtractDigits(n);
|
|
if (!NextPermutation(digits)) {
|
|
return -1;
|
|
} else {
|
|
var result = 0l;
|
|
foreach (var digit in digits) {
|
|
result *= 10;
|
|
result += digit;
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
}
|