将int值拆分为单独的数字 [英] split int value into separate digits

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

问题描述

我想将我的int值拆分成数字。例如,如果没有。是542,结果应该是5,4,2。

I want to split my int value into digits. eg if the no. is 542, the result should be 5,4,2.

我有2个选项。
1)将int转换为String&然后通过使用getCharArray(),我可以有单独的字符&然后我将它们转换回int值。

I have 2 options. 1) Convert int into String & then by using getCharArray(), i can have separate characters & then i will convert them back into int values.

2)将int转换为String,而不将其转换为char数组,迭代它&得到所有数字。

2) Convert int into String, without converting it into char array, iterate it & get all digits.

还有其他方法可以解决问题。如果没有,哪个选项会很快?

Is there any other way to solve the problem. If not, which of the option will be fast?

推荐答案

List<Integer> digits(int i) {
    List<Integer> digits = new ArrayList<Integer>();
    while(i > 0) {
        digits.add(i % 10);
        i /= 10;
    }
    return digits;
}

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

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