【发布时间】:2018-12-21 11:11:04
【问题描述】:
我想编写一个方法,返回数字 (num) 的数字 (place),而 不使用 数组仅循环和条件。
例如:
- 对于输入
num = 17489、place = 1,该方法返回9 - 但是如果索引不存在在like
num = 17489,place = 6返回-1
如果我设置i = 0,我的代码中的某些内容不起作用 case 1) 工作但 2) 否
如果我设置i = 1 case 2) 工作但 1) 否
请帮忙找出问题所在
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;
}
【问题讨论】:
-
对英语有基本的了解会很有帮助。真的很难理解什么有效,什么无效。除此之外,请明确“不工作”的实际含义。
-
@HimBromBeere 在我的代码中如果我设置 i=1 并输入 1-num 长度之间的任何索引它可以工作问题是如果我输入 iindex>num 长度例如 14879,5 返回 1 原因就是num 中的最后一位,但如果我输入 14879,6 它仍然返回 1 insted of -1