Java 返回数字的第 n 位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19194257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return the nth digit of a number
提问by Joey
public class Return {
public static void main(String[] args) {
int answer = digit(9635, 1);
print("The answer is " + answer);
}
static void print(String karen) {
System.out.println (karen);
}
static int digit(int a, int b) {
int digit = a;
return digit;
}
}
Create a program that uses a function called digitwhich returns the value of the nth digit from the right of an integer argument. The value of n should be a second argument.
创建一个程序,该程序使用名为digit的函数,该函数返回整数参数右侧的第 n 个数字的值。n 的值应该是第二个参数。
For Example: digit(9635, 1)
returns 5
and digit(9635, 3)
returns 6
.
例如:digit(9635, 1)
返回5
和digit(9635, 3)
返回6
。
采纳答案by Bohemian
Without spoon-feeding you the code:
不用勺子喂你代码:
The nth digit is (the remainder of dividing by 10n) divided by 10n-1
第 n 个数字是(除以 10 n的余数)除以 10 n-1
If you wanted an iterative approach:
如果您想要一种迭代方法:
Loop n times, each time assigning to the number variable the result of dividing the number by 10.
After the loop, the nth digit is the remainder of dividing the number by 10.
循环 n 次,每次将数字除以 10 的结果赋给 number 变量,
循环后第 n 位为数字除以 10 的余数。
--
——
FYI The remainder operator is %
, so eg 32 % 10 = 2
, and integer division drops remainders.
仅供参考 余数运算符是%
,例如32 % 10 = 2
,整数除法丢弃余数。
回答by SpringLearner
The other way is convert the digit into array and return the nth index
另一种方法是将数字转换为数组并返回第 n 个索引
static char digit(int a,int b)
{
String x=a+"";
char x1[]=x.toCharArray();
int length=x1.length;
char result=x1[length-b];
return result;
}
Now run from your main method like this way
现在像这样从你的主要方法运行
System.out.println("digit answer "+digit(1254,3));
output
输出
digit answer 2
回答by Arun Chandrasekhara Pillai
static int dig(int a, int b) {
int i, digit=1;
for(i=b-1; i>0; i++)
digit = digit*10;
digit = (a/digit) % 10;
return digit;
}
回答by Randa Sbeity
Convert number to string and then use the charAt() method.
将数字转换为字符串,然后使用charAt() 方法。
class X{
static char digit(int a,int n)
{
String x=a+"";
return x.charAt(n-1);
}
public static void main(String[] args) {
System.out.println(X.digit(123, 2));
}
}
You may want to double check that the nth position is within the length of the number:
您可能需要仔细检查第 n 个位置是否在数字的长度内:
static char digit(int a, int n) {
String x = a + "";
char digit='##代码##' ;
if (n > 0 && n <= x.length()) {
digit = x.charAt(n - 1);
}
return digit;
}