从Java中的int获取数字的特定数字 [英] Get a specific digit of a number from an int in Java

查看:30
本文介绍了从Java中的int获取数字的特定数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
返回整数的第一位

在我的 java 程序中,我将一个数字存储在一个数组中.

In my java program, I store a number in an array.

p1Wins[0] = 123;

我如何检查p1Wins[0] 的第一位数字?还是第二个或第三个?我只需要能够找到任何特定数字的值.

How would I check the first digit of p1Wins[0]? Or the second or third? I just need to be able to find the value of any specific digit.

谢谢!

推荐答案

模块化算术可以用来完成你想要的.例如,如果您将 123 除以 10,然后取余数,您将得到第一个数字 3.如果您将 123 除以 100,然后将结果除以 10,您将得到第二个数字 2.更一般地,数字的n-th位数字可以通过公式(number/base^(n-1)) % base获得:

Modular arithmetic can be used to accomplish what you want. For example, if you divide 123 by 10, and take the remainder, you'd get the first digit 3. If you do integer division of 123 by 100 and then divide the result by 10, you'd get the second digit 2. More generally, the n-th digit of a number can be obtained by the formula (number / base^(n-1)) % base:

public int getNthDigit(int number, int base, int n) {    
  return (int) ((number / Math.pow(base, n - 1)) % base);
}

System.out.println(getNthDigit(123, 10, 1));  // 3
System.out.println(getNthDigit(123, 10, 2));  // 2
System.out.println(getNthDigit(123, 10, 3));  // 1

这篇关于从Java中的int获取数字的特定数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆