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

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

大家好,欢迎来到IT知识分享网。

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

希望能帮上忙。

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/52201.html

(0)
上一篇 2024-08-14 17:15
下一篇 2024-08-14 18:33

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信