将数组中的整数拆分为单个数字
我有一个数组:
int test[]={10212,10202,11000,11000,11010};
我想将 inetger 值拆分为单独的数字,并将它们作为单独的元素放入一个新数组中,这样我的数组现在是:
int test2[]={1,0,2,1,2,1,0,2,0,2,1,1,0,0,0,1,1,0,0,0,1,1,0,1,0};
我将如何做到这一点?我正在用java做这个。
谢谢。
I have an array:
int test[]={10212,10202,11000,11000,11010};
I want to split the inetger values to individual digits and place them in a new array as individual elements such that my array now is:
int test2[]={1,0,2,1,2,1,0,2,0,2,1,1,0,0,0,1,1,0,0,0,1,1,0,1,0};
How would i go about doing that? I'm doing this in java.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
通过将条目的最低位数字放置到数组列表的“前面”,因此位于前面的低位数字/条目的前面,这将完全达到您想要的目的。
如果您需要将其放在数组中,ArrayList 有一个 toArray 方法。
This will do exactly what you want by placing the lowest order digit of an entry into the "front" of an arraylist, and therefore in front of the previous low order digits/entries.
If you need it to be in an Array, ArrayList has a toArray method.
您可以按照 Mark 的建议进行操作,或者将它们转换为
String
来获取单个数字:由于仍然涉及字符串的更内存有效的方法是将所有数字保留为一个字符串并计算 < code>int 动态值:
请注意,CheesePls 解决方案是正确的解决方案,因为它按照预期使用数学。我的只是为了菜鸟(并且只是为了提供解决问题的另一种方法)..
You can go as suggested by Mark, or convert them to
String
to get the single digits:As more memory efficient approach that still involves string would be to keep all the digits as just one string and calculate the
int
value on the fly:Mind that CheesePls solution is the right one because it uses math as it is intended to be used. Mine is just for noobs (and just to give another approach to the problem)..
几乎是一行(如果我们假设有一个开箱即用的函数用于将字符串数组转换为整数数组):
Almost one-liner (if we assume that there is an out of the box function for converting array of strings to array of integers):
您可以将每个整数除以 10,然后将分数与余数分开。将分数乘以 10,使其再次成为整数,并将其放入新数组中。重复此操作,直到用完数字。重复此操作,直到用完输入数组中的整数。
You'd take each integer, divide by 10 and separate the fraction from the remainder. multiply the fraction by 10 to make it an integer again and put it into your new array. Repeat until you run out of digits. Repeate until you run out of integers in your input array.
尝试这样的事情。
我没有测试过这段代码。
此代码将(自然地)忽略前导零并回填整数数组。获得正确的数组大小可能是一个问题。
Try something like this.
I have not tested this code.
This code would ignore leading zeroes (Naturally) and backfill the array of integers. Getting the proper size for the array could be a problem.
这个(未经测试):
This (untested):
这是一种用字符串来实现的方法。性能不是特别好,但是(我希望)易于理解。
Here's a way to do it with strings. Not particularly performant, but (I hope) easy to understand.