爪哇; int[] 到 int
我如何以特殊的方式将整数数组转换为整数?
例如,如何将 { 1, 9, 9, 0 } 转换为 1990?
How would I convert an array of integers into an integer, but in a special way?
For example, how would I convert { 1, 9, 9, 0 } into 1990?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用:
这就是我的实现方式。它获取每个元素,如果它是数组的第一个元素,则将其乘以 10^(数组的长度 - 1 - theCurrentElement),并将所有元素添加到结果中。它适用于所有尺寸。基本上是将第 100 个乘以 100,第 10 个乘以 10,依此类推。
例如: char = {1,2,3} 会将 1 乘以 100 2 乘以 10 3 乘以 1,然后得到所有结果的总和并得到 123。
Use:
This is how I implemented it. It takes each element, and if it is the first of the array it multiplies it by 10^(length of the array - 1 - theCurrentElement) and it adds all to the result. It works for all sizes. Basically multiplying the 100th by 100, 10th by 10 and so on.
For example: char = {1,2,3} would multiply 1 by 100 2 by 10 3 by 1 and get the sum of all and get 123.
这适用于任何大小的整数数组
This will work for any size integer array
看到不必要的复杂解决方案令人沮丧,涉及 Math.pow、String 等。甚至还出现了正则表达式和第三方库!
您所需要的只是一个循环和乘以 10:
这当然假设 arr 的元素在 0-9 范围内;但无论如何,在这种情况之外的正确行为是不确定的。
它还假设数组的数字可以转换为整数而不会溢出;但由于问题询问如何转换为整数,因此溢出行为也是未定义的。
请注意,您可以通过与字符串连接解决方案类似的方式处理“element > 9”情况,方法是计算出如何您必须将
num
转换为多个数字:我认为这不是处理元素中多个数字的最合适方法;至少应该指定行为。我只是指出您不需要诉诸字符串来处理它。
It is upsetting to see the unnecessarily complex solutions, involving
Math.pow
,String
etc. Even regex and third party libraries make an appearance!All you need is a loop and multiplication by 10:
This of course assumes that the elements of
arr
are in range 0-9; but then the correct behavior outside that case is undefined anyway.It also assumes that the array's digits can be converted to an integer without overflow; but since the question asks about converting to an integer, overflow behavior is also undefined.
Note that you can handle the "element > 9" case in the similar way to the string concatenation solution by working out how many digits you have to shift
num
by:I don't think this is the most appropriate way to handle multiple digits in an element; at the very least the behaviour should be specified. I'm just pointing out that you don't need to resort to strings to handle it.
假设您的数字是
Integer[]
而不是原始的int[]
并且有 Commons Lang Library 您可能会发现下面的一行有用或者如果整数太大而无法放入
int
中,请使用BigInteger
Assuming you have digits in
Integer[]
instead of primitiveint[]
and have Commons Lang Library you may find following one liner usefulOr if the integer is too big to fit in
int
useBigInteger
我不确定在 Java 中,但在伪 .NET 代码中:
I am not sure in Java, but in pseudo .NET code: