Java将字符串转换为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操作或循环),然后向后循环创建列表。

希望能帮上忙。

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java盘鱼宴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值