Home > Blockchain >  How can a digit of an int variable be taken and stored in a LinkedList separately?
How can a digit of an int variable be taken and stored in a LinkedList separately?

Time:12-15

For example, if i had a 17 digit integer variable. How can i take each digit and store it in a different node separately? That way i have a LinkedList that has 17 as it's length.

I thought there was a function similar to charAt but i could not find one.

CodePudding user response:

What I would do is the following:

  1. Convert int to `String
  2. Convert each char of this String back to an int and add it to your list

A method to do this can look like this:

private static LinkedList<Integer> getDigitsAsLinkedList(int value) {
    LinkedList<Integer> result = new LinkedList<>();
    
    String valueString = Integer.toString(value);
    
    for(char digitAtPosition : valueString.toCharArray()) {
        result.add(Character.getNumericValue(digitAtPosition));
    }
    
    return result;
}

Be aware that Integer.MAX_VALUE is only 2147483647 whis is only 10 digits. If you want higher numbers, you need to use other types.

Example for usage of the method above:

public static void main(String[] args) {
    System.out.println(getDigitsAsLinkedList(1234567890));
}

This results in an output of [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].

CodePudding user response:

Assuming it's 17 digits, you'd be using long instead of int. Now, you've not mentioned whether the list must be integer or character, for each digit. So, for int output:

LinkedList<Integer> numToIntList(Long num) {
    LinkedList<Integer> result = new LinkedList<>();
    while (num > 0) {
        result.push((int) (num % 10));  // push because we're getting digits in reverse, so this would ensure proper order
        num = num / 10;
    }
    return result;
}

Similarly, a bit extra effort for char:

LinkedList<Character> numToCharList(Long num) {
    LinkedList<Character> result = new LinkedList<>();
    while (num > 0) {
        result.push(Character.forDigit((int) (num % 10), 10));
        num = num / 10;
    }
    return result;
}

Note: in case you have numbers within int range you won't need explicit casting for num % 10 since it's already an integer.

  • Related