Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace FilterByPalindromicTask
- {
- /// <summary>
- /// Provides static method for working with integers array.
- /// </summary>
- public static class ArrayExtension
- {
- /// <summary>
- /// Returns new array that contains only palindromic numbers from source array.
- /// </summary>
- /// <param name="source">Source array.</param>
- /// <returns>Array of elements that are palindromic numbers.</returns>
- /// <exception cref="ArgumentNullException">Throw when array is null.</exception>
- /// <exception cref="ArgumentException">Throw when array is empty.</exception>
- /// <example>
- /// {12345, 1111111112, 987654, 56, 1111111, -1111, 1, 1233321, 70, 15, 123454321} => { 1111111, 123321, 123454321 }
- /// {56, -1111111112, 987654, 56, 890, -1111, 543, 1233} => { }.
- /// </example>
- public static int[] FilterByPalindromic(int[]? source)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source), "array is null");
- }
- if (source.Length == 0)
- {
- throw new ArgumentException("array length is null", nameof(source));
- }
- int length = source.Length;
- int[] result = new int[length];
- int k = 0;
- for (int i = 0; i < length; i++)
- {
- if (IsPalindromicNumber(source[i]))
- {
- result[k] = source[i];
- k++;
- }
- }
- Array.Resize(ref result, k);
- return result;
- }
- private static bool IsPalindromicNumber(int number)
- {
- if (number < 0)
- {
- return false;
- }
- byte length = IntLength(number);
- return IsPalindromicNumberCore((int)Math.Pow(10, length - 1));
- bool IsPalindromicNumberCore(int pow)
- {
- if (number < 10)
- {
- return true;
- }
- if (number / pow != number % 10)
- {
- return false;
- }
- number = (number % pow) / 10;
- return IsPalindromicNumberCore(pow / 100);
- }
- }
- private static byte IntLength(int number) =>
- number switch
- {
- < 10 => 1,
- < 100 => 2,
- < 1000 => 3,
- < 10000 => 4,
- < 100000 => 5,
- < 1000000 => 6,
- < 10000000 => 7,
- < 100000000 => 8,
- < 1000000000 => 9,
- _ => 10
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement