从Java的一个int获取了一些具体的数字 [英] Get a specific digit of a number from an int in Java

查看:166
本文介绍了从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 。如果通过 100 123 的整数除法,然后除以 10 ,你会得到的第二位 2 。更一般地, N -th若干位可通过公式来获得(数/碱^(N-1))%碱

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天全站免登陆