I want to write a method that returns digit of a number (num
) by index (place
) while not using array only loops and conditions.
For example:
- For the input
num = 17489
,place = 1
the method returns9
- But if the index does not exist in the like
num = 17489
,place = 6
return-1
something in my code doesn't work if I set i = 0
case 1) work but 2) no
if i set i = 1
case 2) work but 1)no
please help figure whats wrong
public static int Digit_by_place(int num, int place)
{
int digit = 0, i = 0;
// the lop run until the place in the
while (num > 0 && i <= place)number
{
digit = num % 10;
num = num / 10;
i++;
// if there is no didgit in the input place return -1
if (i < place && num == 0)
{
return -1;
}
// return the last digit from left (the bigest)
if (num == 0 && digit > 0 && i == place)
{
return digit;
}
}
return digit;
}