Мы можем использовать тот факт, что int
может содержать не более 10
цифр.
Код:
public static int Digit_by_place(int num, int place) {
if (place <= 0 || place > 10) // place must be in [1..10] range
return -1;
else if (num == 0) // special case num == 0
return place == 1 ? 0 : -1;
for (int i = 1; i < place; ++i)
num /= 10;
return num == 0 ? -1 : Math.Abs(num % 10);
}
Демонстрация:
using System.Linq;
...
Tuple<int, int>[] tests = new Tuple<int, int>[] {
Tuple.Create( 17489, 1),
Tuple.Create( 17489, 2),
Tuple.Create( 17489, 3),
Tuple.Create( 17489, 4),
Tuple.Create( 17489, 5),
Tuple.Create( 17489, 6),
Tuple.Create(-17489, 1),
Tuple.Create(-17489, 6),
Tuple.Create( 17489, 0),
Tuple.Create( 17489, -1),
Tuple.Create(-17489, -1),
Tuple.Create( 17489, 5),
Tuple.Create(-17489, 5),
Tuple.Create( 0, 1),
Tuple.Create( 0, 4),
};
var report = string.Join(Environment.NewLine, tests
.Select(test =>
$"Digit_by_place({test.Item1,6}, {test.Item2,2}) = {Digit_by_place(test.Item1, test.Item2),2}"));
Console.Write(report);
Результат:
Digit_by_place( 17489, 1) = 9
Digit_by_place( 17489, 2) = 8
Digit_by_place( 17489, 3) = 4
Digit_by_place( 17489, 4) = 7
Digit_by_place( 17489, 5) = 1
Digit_by_place( 17489, 6) = -1
Digit_by_place(-17489, 1) = 9
Digit_by_place(-17489, 6) = -1
Digit_by_place( 17489, 0) = -1
Digit_by_place( 17489, -1) = -1
Digit_by_place(-17489, -1) = -1
Digit_by_place( 17489, 5) = 1
Digit_by_place(-17489, 5) = 1
Digit_by_place( 0, 1) = 0
Digit_by_place( 0, 4) = -1