英文:
How can I turn a large integer into an array of successive two-digit integers?
问题
我想将一个n位整数j(其中n是2的幂次)转换为一个int[]数组,其中每个int[i]是由j的连续数字组成的两位整数。
所以如果
int j = 357642466853;
int[] digArray = {35, 76, 42, 46, 68, 53};
我开始尝试以下方法,但陷入了困境。如果我使用String.valueOf或.charAt,它最终会将这些相应的数据类型发送到数组,尽管我希望它是一个int[]数组。
int[] digArray = new int[intLength/2]; //intLength只是n
for(int i = 0; i < intLength; i += 2) {
digArray[i/2] = (String.valueOf(j).charAt(i)); //注意这还不完整,因为我甚至不知道如何在第二位数字上进行连接。
}
也许我需要创建一个string[]数组,然后在完成后将其转换为int[]数组?
谢谢。
英文:
I want to take an n-digit integer j (where n is a power of two) and turn it into an int[ ] where each int[ i ] is a two-digit integer set by the successive digits of j.
So if
int j = 357642466853
int[ ] digArray = {35, 76, 42, 46, 68, 53}
I started down the following route but have gotten bogged down. If I use String.valueOf or .charAt it ends up sending those respective data types to the array, even though I want it to be an int[].
int[] digArray = new int[intLength/2] //intLength is just n
for(int i = 0; i < intLength; i += 2) {
digArray[i/2] = (String.valueOf(j).charAt(i)) //Note this isn't complete as I don't even know how to concatenate on the second digit.
}
Possibly I need to make a string[] and then once I'm done convert it into an int[]?
Thanks.
答案1
得分: 2
你可以在这里使用取模运算:
long j = 357642466853L;
long[] digArray = new long[(int)(Math.log10(j) / 2) + 1];
for (int i=digArray.length - 1; i >= 0; --i) {
digArray[i] = j % 100L;
j /= 100;
}
System.out.println(Arrays.toString(digArray));
这将打印出:
[35, 76, 42, 46, 68, 53]
英文:
You could use the modulus here:
long j = 357642466853L;
long[] digArray = new long[(int)(Math.log10(j) / 2) + 1];
for (int i=digArray.length - 1; i >= 0; --i) {
digArray[i] = j % 100L;
j /= 100;
}
System.out.println(Arrays.toString(digArray));
This prints:
[35, 76, 42, 46, 68, 53]
答案2
得分: 1
另一种实现方式如下:
for (long v : new long[]{ 357642466853L, 1234L, 29228912L}) {
System.out.println(v + " " + Arrays.toString(longToGroups(v)));
}
public static long[] longToGroups(long val) {
int exp = (int)Math.log10(val);
exp -= (exp % 2); // 调整为奇数位长的情况
long start = (long)(Math.pow(10, exp));
return LongStream
.iterate(start, i -> i > 0, i -> i / 100)
.map(i -> (val / i) % 100).toArray();
}
输出结果为:
357642466853 [35, 76, 42, 46, 68, 53]
1234 [12, 34]
29228912 [29, 22, 89, 12]
英文:
And yet another way to do it.
for (long v : new long[]{ 357642466853L, 1234L,29228912L}) {
System.out.println(v + " " + Arrays.toString(longToGroups(v)));
}
public static long[] longToGroups(long val) {
int exp = (int)Math.log10(val);
exp -= (exp % 2); // adjust for odd length longs
long start =(long)(Math.pow(10,
exp));
return LongStream
.iterate(
start,
i -> i > 0, i -> i / 100)
.map(i -> (val / i) % 100).toArray();
}
Prints
357642466853 [35, 76, 42, 46, 68, 53]
1234 [12, 34]
29228912 [29, 22, 89, 12]
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论