将int转换为数组而不将其转换为String [英] Converting an int into an array without converting it to a String

查看:167
本文介绍了将int转换为数组而不将其转换为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java编程,想将一个int转换成一个数组。例如,我想将122转换为{1,2,2}。您知道这是如何工作的吗?提前致谢。我不允许将其转换为字符串。

I am programming in Java and want to convert an int into an array. For example I want to convert 122 into {1, 2, 2}. Do you have an idea how this works? Thanks in advance. I am not allowed to convert it into a string.

推荐答案

下面的示例使用纯算术方法(无需将数字转换为字符串) ):

The following example uses pure arithmetical approach (without converting the number to string):

int number = 122;
List<Integer> digitList = new LinkedList<>();

while(number > 0) {
  int d = number % 10; //get last digit
  digitList.add(0, d);
  number = number / 10; //omit last digit
}

Integer[] digits = digitList.toArray(new Integer[0]);
System.out.println(Arrays.toString(digits));

这篇关于将int转换为数组而不将其转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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