如何获取int数字的单独数字? [英] How to get the separate digits of an int number?

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

问题描述

我的数字有1100,1002,1022等。我想有个别数字,例如第一个数字1100我想要1,1,0,0。

I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.

如何用Java获取它?

How can I get it in Java?

推荐答案

要做到这一点,你将使用(mod)运算符。

To do this, you will use the % (mod) operator.

int number; // = some int

while (number > 0) {
    print( number % 10);
    number = number / 10;
}

mod运算符将为您提供对数字进行int除法的余数。

The mod operator will give you the remainder of doing int division on a number.

所以,

10012 % 10 = 2

因为:

10012 / 10 = 1001, remainder 2

注意:正如Paul所说,这将以相反的顺序给你数字。您需要将它们推入堆栈并以相反的顺序将它们弹出。

Note: As Paul noted, this will give you the numbers in reverse order. You will need to push them onto a stack and pop them off in reverse order.

以正确的顺序打印数字的代码:

Code to print the numbers in the correct order:

int number; // = and int
LinkedList<Integer> stack = new LinkedList<Integer>();
while (number > 0) {
    stack.push( number % 10 );
    number = number / 10;
}

while (!stack.isEmpty()) {
    print(stack.pop());
}

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

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