java - 将 ArrayList 元素向右移动

标签 java arraylist

全面披露这是一个我没有答对的面试问题。问题如下:

    /*
     * If you have an integer that is too large to be stored as a built-in type
     * like an int or double, you can represent it as an array of single digits.
     * Write a function that will increment such a number by 1. For example, the
     * number 1,235 would be represented as [1, 2, 3, 5] in an array. The
     * function should take the array [1, 2, 3, 5] as input and return the array
     * [1, 2, 3, 6].
     */

我有一个 ArrayList,其中每个元素代表以 10 为基数的数字。我想创建一个方法来增加数字,然后输出增加的数字。所以我有这个:

package start;

import java.util.ArrayList;
import static java.lang.System.out;

public class InputArray {

    private ArrayList<Integer> value;

    public InputArray(ArrayList<Integer> value) {
        this.value = value;
    }


    private ArrayList<Integer> returnBigNum() {

        ArrayList<Integer> input = this.value;
//      input.set(0,0) // this won't work

        for (int i = input.size() - 1; i >= 0; i--) {

            Integer temp = input.get(i);

            temp++;

            if (temp.equals(10)) {
                input.set(i, 0);
            } else {
                input.set(i, temp);
                return input;
            }
        }
        return input;
    }

    public static void main(String[] args) {

        InputArray ia1 = new InputArray(new ArrayList<Integer>(){{
            add(3);add(9);add(9);add(9);add(9);
        }});

        InputArray ia2 = new InputArray(new ArrayList<Integer>(){{
            add(9);add(9);add(9);
        }});

        ArrayList<Integer> result1 = ia1.returnBigNum();
        out.println(result1);

        ArrayList<Integer> result2 = ia2.returnBigNum();
        out.println(result2);
    }

}

我遇到的问题是输入全是 9,例如 999、9999、999999 等。 当输入 = 999 时,我最终得到 000。

因此,一种快速解决方案是在方法开头的第 0 个位置添加一个元素,然后您就有了要迭代的最终元素。但问题是,如何将所有元素向右移动?如果计算量太大,那么更好的解决方法是什么?

要将事物向右移动,这就是必需的吗?

http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html void add(int 索引, E 元素) 在此列表中的指定位置插入指定元素。

这不是计算成本很高吗?

最佳答案

您只需使用以下命令即可将 0 添加到列表的开头:

//      the element to add
//           |
//           V
input.add(0, 0);
//        ^
//        |
// the index to add it at

Hereadd 方法重载的文档。

关于java - 将 ArrayList 元素向右移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29268413/

相关文章:

java - 基础 ClearCase 失败。退出代码=1。 IOException : cleartool did not return the expected exit code

java - 在 java 中从 String 中读取元音的数量

java - 对具有两个参数的方法进行双冒号赋值

java - java列表的数组索引越界异常错误

java - 防止数组列表中出现重复项

java - 为什么 println() 方法被执行两次而不是一次?

java - 谷歌工具包中的 Xpath 与 selenium webdriver

java - java中分割字符串值后如何更正返回值?

javascript - 如何删除嵌套数组中的特殊字符?

java - 如何在java中声明匿名数组列表?