大家好,我目前正在尝试将字符串反向转换为 arrayList,然后删除所有尾随零 例如“001203”转换为(3,0.2,1,0,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);
}
}
其他几个选项:
更改内部循环,以便在列表上向后迭代,并删除零,直到找到非零值
首先修剪所有前导零(例如使用正则表达式操作或循环),然后向后循环以创建列表。
希望有帮助。
关于java 将字符串转换为int并删除尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30397998/