Jackson
Jackson

Reputation: 31

How can I turn a large integer into an array of successive two-digit integers?

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.

Upvotes: 1

Views: 517

Answers (2)

WJS
WJS

Reputation: 40044

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]

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521389

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]

Upvotes: 2

Related Questions