1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-22 08:33:48 +01:00
CodeWars/4kyu/next_bigger_with_same_digits/solution.cs
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

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;
}
}
}