龙空技术网

Java将字符串转换为int并移除回零

Java盘鱼宴 63

前言:

当前小伙伴们对“int数组转int”可能比较注重,咱们都想要分析一些“int数组转int”的相关资讯。那么小编同时在网摘上收集了一些有关“int数组转int””的相关文章,希望你们能喜欢,大家一起来了解一下吧!

大家好,我现在正试图将字符串反向转换为数组列表,然后删除任何尾随零,例如“001203”转换为(3,0.2,1,0),然后(3,0,2,1)

我的代码是

public convert(String nums) {    List = new ArrayList<Integer>();  // create arraylist    for (int i = nums.length(); i >= 0; i--) { //convert to int        int j = Integer.parseInt(digits);        List .add(j);        for (Iterator<Integer> k = List .iterator(); k.hasNext();) {  //remove trailing zeros            if (k.next().equals(0)) {                k.remove();            }        }    }

此代码当前删除所有0,而不是尾随零。这意味着我的输出是(3,2,1)而不是(3,0,2,1);

如有任何帮助,敬请提前感谢。

方法的问题是,在内部循环中,不管它在列表中的位置如何,都要移除零。

有多种方法可以实现你想要的。这里有一个使用单个循环的方法(没有字符串或集合操作来为您反转列表):

String nums = "001203";    List<Integer> list = new ArrayList<>();    // a boolean flag to help check for leading zeroes    // set it to true first i.e. assume there are leading zeroes    boolean checkLeadingZeroes = true;    // Ignore leading zeroes during iteration,    // and append to list in reverse order    for (int i=0; i < nums.length(); i++){        int n = Integer.parseInt(nums.charAt(i)+"");        // only check for leading zeroes if flag is true        if (checkLeadingZeroes){            // If flag is set to false here, you've found the first non-zero            checkLeadingZeroes = (n == 0);        }        if (!checkLeadingZeroes) {            /* If flag is false, n is not a leading zero             * Add n to the beginning of your list (index 0)             */            list.add(0, n);        }    }

其他几种选择:

1.更改内循环,以便向后迭代列表,并移除零,直到找到非零值为止。

2.先修剪所有前导零(例如使用regex操作或循环),然后向后循环创建列表。

希望能帮上忙。

标签: #int数组转int