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

80 阅读2分钟

大家好,我现在正试图将字符串反向转换为数组列表,然后删除任何尾随零,例如“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操作或循环),然后向后循环创建列表。

希望能帮上忙。

下面是博主剪辑的视频资料 可能与文章无关 希望大家可以支持一下哦!谢谢大家支持!

UP主:我只需一小时带你玩转Git&Github B友直呼:菜鸡这不是有手就行?

【面试必备】阿里资深架构师详解 2021最新 Java秒杀系统高性能高并发实战项目

Java零基础小白看完我这个系列视频都可以自己做实战项目啦!拿捏呢!

2021最新版lntellij IDEA 安装、配置、环境变量教学

2021最新算法训练营:左神带你 爆刷LeetCode算法(1000题) 进大厂的必修算法课程!

B站首发 花费12980巨资购买的 微服务SpringCloud Alibaba全集