Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace NextBiggerTask
- {
- public static class NumberExtension
- {
- /// <summary>
- /// Finds the nearest largest integer consisting of the digits of the given positive integer number and null if no such number exists.
- /// </summary>
- /// <param name="number">Source number.</param>
- /// <returns>
- /// The nearest largest integer consisting of the digits of the given positive integer and null if no such number exists.
- /// </returns>
- /// <exception cref="ArgumentException">Thrown when source number is less than 0.</exception>
- public static int? NextBiggerThan(int number)
- {
- int n = number;
- int length = NumberOfDigit(number);
- var numberArray = new int[length - 1];
- for (int i = length; i > 0; i--)
- {
- numberArray[i] = n % 10;
- n /= 10;
- }
- int position = -1;
- for (int i = length; i > 0; i--)
- {
- if (numberArray[i] > numberArray[i - 1])
- {
- position = i;
- break;
- }
- }
- if (position == -1)
- {
- return 0;
- }
- var endOfNumberArray = numberArray[position..length];
- if (endOfNumberArray == BubbleSortLess(endOfNumberArray))
- {
- position--;
- endOfNumberArray = numberArray[position..length];
- }
- for (int i = 2; i < endOfNumberArray.Length; i++)
- {
- int firstGreat = endOfNumberArray[1];
- if (endOfNumberArray[i] > endOfNumberArray[0] && endOfNumberArray[i] < firstGreat)
- {
- int temp = endOfNumberArray[0];
- endOfNumberArray[0] = endOfNumberArray[i];
- endOfNumberArray[i] = temp;
- }
- }
- var result = new int[length - 1];
- for (int i = 0; i < position; i++)
- {
- result[i] = numberArray[i];
- }
- result[position] = endOfNumberArray[0];
- var foo = new int[length - 1 - 1 - position];
- foo = BubbleSortGreat(foo);
- Array.Copy(endOfNumberArray, 1, foo, 0, length - 1 - 1 - position);
- for (int i = position + 1; i < length; i++)
- {
- result[i] = foo[i];
- }
- return ArrayToInt(result);
- }
- private static int NumberOfDigit(int number)
- {
- int i = 0;
- while (number > 0)
- {
- number /= 10;
- i++;
- }
- return i;
- }
- private static int ArrayToInt(int[] arr)
- {
- int number = 0;
- for (int i = 0; i < arr.Length; i++)
- {
- number *= 10;
- number += arr[i + 1];
- }
- return number;
- }
- private static int[] BubbleSortLess(int[] arr)
- {
- int n = arr.Length;
- for (int i = 0; i < n - 1; i++)
- {
- for (int j = 0; j < n - i - 1; j++)
- {
- if (arr[j] < arr[j + 1])
- {
- int temp = arr[j];
- arr[j] = arr[j + 1];
- arr[j + 1] = temp;
- }
- }
- }
- return arr;
- }
- private static int[] BubbleSortGreat(int[] arr)
- {
- int n = arr.Length;
- for (int i = 0; i < n - 1; i++)
- {
- for (int j = 0; j < n - i - 1; j++)
- {
- if (arr[j] > arr[j + 1])
- {
- int temp = arr[j];
- arr[j] = arr[j + 1];
- arr[j + 1] = temp;
- }
- }
- }
- return arr;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement