We have List<Integer> lista=new Arraylist<>();
where list is of size n and in each position it has an integer, that is, lista.get(0)==2,lista.get(1)==8...,lista.get(n)==6
.
And I would like to multiply an integer, say k , by the entire number that makes up the list, ie k *(28...6).
How could I do it?
To concatenate all the elements you can iterate through the list and use the
.append(Int n)
StringBuilder method .At the end of the tour, the StringBuilder will have as value the concatenation of the digits of the numbers and you can create an Integer using
Integer.valueOf(String string)
The operation
valueOf
is not safe, it can throw NumberFormatException for strings like "12a1" or "12-12", so if you had negative values you would get such an exception.In turn, as @Arie CwHat comments in @Einer's answer , creating a from a variable number of digits and potentially greater than the maximum precision is not a good idea.
Integer
To avoid this problem we can use
BigInteger
, which does not have a defined maximum precision but can grow from-2^Integer.MAX_VALUE
(exclusive) to2^Integer.MAX_VALUE
(inclusive), whereInteger.MAX_VALUE = 2^32 - 1
(Extracted from Is there a upper bound to biginteger? )Well then you will have to concatenate each number in the list and then convert it to
double
:Concatenating a list of
n
elements it is very likely that this maximum Integer value will be exceeded, so I use itdouble
to avoid a stack overflow due to the Integer limit of2 147 483 648
nine digits.Update:
You can also use the class
BigInteger
that does not have a defined limit likedouble
:This is an example of how you could do it: (but there are many other ways)