将整数的 ArrayList 转换为一个 int 的最简单方法是什么,列表中的第一个整数是 int 中的第一个数字,等等。在 Java 中?
例如整数的 ArrayList:1 4 6 7 8 3 8
变为 int 值 1467838
The simplest way in Java is:
int total = 0;
for (Integer i : list) { // assuming list is of type List<Integer>
total = 10*total + i;
}
For example, if the list consists of 1 4 6 7 8 3 8, you get:
total = 0
total = 10*0 + 1 = 1
total = 10*1 + 4 = 14
total = 10*14 + 6 = 146
...
total = 10*146783 + 8 = 1467838
which is the correct answer.
注意:最简单的并不总是最有效的。这是在 java 中,因为您没有指定语言。但你可以这样做:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(4);
list.add(6);
for (Integer x : list) {
s += x.toString();
}
Integer finalResult = Integer.parseInt(s);
编辑:为了取悦所有在评论中注意到这一点的人,如果你真的担心效率但由于某种原因想要使用这个字符串方法,应该这样做:
StringBuilder sb = new StringBuilder();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(4);
list.add(6);
String s;
for (Integer x : list) {
sb.append(x.toString());
}
Integer finalResult = Integer.parseInt(sb.toString());
在第一个示例中,为简单起见没有使用 StringBuilder,因为这看起来像是一项家庭作业。
假设 C#(你没有指定 :-),但一般算法可以在你需要的任何语言中工作:
int num = 0;
for( int i = 0 ; i < list.Count ; i++ )
{
num *= 10;
num += (int)list[i];
}
显然,代码假定生成的数字足够小,可以用 int 表示,并且 ArrayList 中的每个项目都介于 0 和 9 之间。
Only handles numbers up to 2 billion or so. Use long, long-long, or your favorite bigint class if you want bigger numbers. Won't work with negative numbers unless they're all negative.
int runningtotal = 0;
foreach(int i in myList) {
runningtotal *= 10;
runningtotal += i;
}
return runningtotal;
另一种解决方案,这将接受大于 9 的数字
List<Integer> list =
int num = Integer.parseInt(list.toString().replaceAll("\\D",""));
int result = 0;
for(int i=list.Count - 1;i>=0;--i)
{
result += list[i] * (int)(Math.Pow((double)10, (double)(list.Count - 1 - i)));
}
Also won't work with negative numbers...you could use Math.Abs() to handle that.
Without knowing which language you want, I think your best approach is to find the sum of 1000000 + 400000 + 60000 + 7000 + 800 + 30 + 8
I am assuming from your question that index 0 of the ArrayList is the most significant value. Your example show the first number being equivalent to 1,000,000.
You could either treat them as characters then concatenate them then parse back to Integer.
Or you can add each item to the result, then multiply the result by ten to set the magnitudes.
Or you can add each element's value * 10^(count-index); where count is the number of elements in the ArrayList.
In Python! Just for fun:
i = int( "".join( [str(z) for z in x] ) )
在哈斯克尔,
listToNumber = foldl (\a b -> a*10 + b) 0
在 Python 中,
def list_to_number(some_list):
return reduce(lambda x, y: x*10 + y, some_list, 0)