简体   繁体   中英

How to represent a 'long' number as nodes in a linked-list [JAVA]

I have a pragmatic task to solve:

Int and Long numbers that we can store in memory cells are limited in size. One way to solve the problem would be to set up a linked-list in which each node in the list will contain one digit from the number so that the number itself will not be kept as a number but as a collection of its' digits- one after the other.

I have to create a Constructor, which gets a 'long' type of number and stores it in a format of a linked list.

By that I mean that if we take the number 233,674,318, the Constructor would create a representation of this number as the following: 2 -> 3 -> 3 -> 6 -> 7 -> 4 -> 3 -> 1 -> 8

Could you please suggest me how can I approach this?

Thank you in advance!

You can extract a number's least significant digit (the one on the right) using the modulo operator. In this case, 233,674,318 % 10 will yield 8 ( % signifies modulo). You can get rid of a number's least significant digit using division. 233,674,318 / 10 will yield 23,367,431 which is like removing the 8 from the number. Using these two operations you can extract all the digits from a number and build a list out of them.

Convert to String and take each char to create nodes

import java.util.*;
import java.util.stream.*

         LinkedList<Integer> getList(long num){
             String[] arr = String.valueOf(num).split("");
             LinkedList<Integer> list = new LinkedList<>();
             list.addAll(Stream.of(arr)
                     .mapToInt(x->Integer.parseInt(x))
                     .boxed()
                     .collect(Collectors.toList()));
             return list;
         }

This is a method you could use. Ultimately, it is a matter of either using the modulus to get every digit or using a split function on the String value of the long number to be then parsed and stored in a LinkedList of Integers.

If you are trying to save memory, as per your question, using integers for the linkedlist would be better as integers only use 32 bits whereas long uses 64 bits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM