Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
Updated
Note that if the next digit does not match the condition, then all calculations and enumeration stop. That is, we do not get the whole array of digits, but calculate the digits one by one, after we have determined whether the new digit increases or decreases compared to the previous digit.
using System;
using System.Collections.Generic;
using static Numbers.NumberAlgorithm;
namespace Numbers
{
public static class NumberAlgorithm
{
public static bool AreDigitsIncreasing(int number)
{
int prevDigit = 0;
int counter = 0;
foreach (int digit in GetDigits(number))
{
if (counter != 0 && prevDigit >= digit)
{
return false;
}
++counter;
prevDigit = digit;
}
return counter > 1;
}
public static bool AreDigitsDecreasing(int number)
{
int prevDigit = 0;
int counter = 0;
foreach (int digit in GetDigits(number))
{
if (counter != 0 && prevDigit <= digit)
{
return false;
}
++counter;
prevDigit = digit;
}
return counter > 1;
}
public static IEnumerable<int> GetDigits(int source)
{
int digit = 0;
int coefficient = (int)Math.Pow(10, GetCountOfDigits(source));
do
{
source -= coefficient * digit;
coefficient /= 10;
digit = source / coefficient;
yield return digit;
} while (coefficient > 1);
}
public static int GetCountOfDigits(int number)
{
return number == 0 ? 1 : (int)Math.Ceiling(Math.Log10(Math.Abs(number) + 0.5));
}
}
class Program
{
private const string DigitsAreIncreasing = "Цифры возрастают слева направо";
private const string DigitsAreDecreasing = "Цифры понижаются слева направо";
private const string DigitsAreMixed = "Цифры не упорядочены";
static void Main(string[] args)
{
int[] numbers = { 123456789, 987654321, 2312, 0 };
for (int i = 0; i < numbers.Length; i++)
{
int number = numbers[i];
string message;
if (AreDigitsIncreasing(number))
{
message = DigitsAreIncreasing;
}
else if (AreDigitsDecreasing(number))
{
message = DigitsAreDecreasing;
}
else
{
message = DigitsAreMixed;
}
Console.WriteLine($"{(i + 1):D2}: Исходное число {number.ToString()}. {message}.");
}
Console.ReadKey();
}
}
}
If the first number is less than the second, then we count in the ascending branch, if not, then in the descending direction, otherwise we return false. The ascending and descending branches sort through the numbers and if the condition is not true, I return false, if they reach the end, they return true.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question