如何从整数中删除所有零? 如果int只是零,它将返回0,但如果不是,则返回一个相同的整数,除非它没有任何0。
我尝试将其传递给String,然后在删除完成后传递给整数,但它再次带有0。
我该怎么做?
public static void main(String[] args) {
// test method removeZeros
test_removeZeros(0); // result = 0
test_removeZeros(2); // result = 2
test_removeZeros(10); // result = 1
test_removeZeros(101); // result = 11
test_removeZeros(10050); // result = 15
test_removeZeros(-30100); // result = -31
System.out.println();
}
private static void test_removeZeros(int n) {
try {
System.out.print("removeZeros (" + n + ") = ");
int res = removeZeros(n);
System.out.println(res);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
private static int removeZeros(int n) {
int finalresult= n;
int result;
String medium;
if (n == 0){
result= 0;
result= finalresult;
} else{
medium= Integer.toString(n);
int x = Integer.parseInt(medium.substring(0));
result= Integer.valueOf(medium);
result= finalresult;
}
finalresult = result;
return finalresult;
}
答案 0 :(得分:1)
Integer.parseInt(Integer.toString(a).replace("0", ""))
上面的单行检查将Int转换为String将所有字符删除为0.然后转换回int。在上面的答案中,a表示int变量。
并且您可能需要在执行此操作之前检查if a != 0
,因为它会抛出NumberFormatException
private static int removeZeros(int a) {
if (a != 0) {
return Integer.parseInt(Integer.toString(a).replace("0", ""))
}
return 0
}
答案 1 :(得分:1)
让我感到沮丧的是,只能使用字符串转换来解决这个问题。这不是必要的,如果你不使用它会更有趣。
相反,您可以递归地解决它:依次遍历每个数字,如果它们非零,则将它们添加到结果中。像这样:
int withoutZeros(int i) {
return withoutZeros(i, 0, 1);
}
int withoutZeros(int remainingDigits, int result, int mul) {
// mul is the multiplier to put the last digit in the right place
// in the result. For instance, if mul is 100, and the last digit
// of remainingDigits is 4, the final result will end with 4??.
// There are no more digits; so return the result.
if (remainingDigits == 0) return result;
int lastDigit = remainingDigits % 10;
// The last digit is a zero, so we don't include in the result.
if (lastDigit == 0) return withoutZeros(i / 10, result, mul);
// Otherwise, add the last digit of i to the result.
// We have to multiply by mul in order to put this digit
// "in the right place" in the result (because this processes
// the digits in reverse order).
// Increase mul for the next iteration.
return withoutZeros(i / 10, result + lastDigit * mul, 10 * mul);
}
由于这是尾递归的,你可以把它写成循环:
int withoutZeros(int i) {
int result = 0;
for (int remainingDigits = i, mul = 1; remainingDigits > 0; remainingDigits /= 10) {
int lastDigit = remainingDigits % 10;
if (lastDigit != 0) {
result += lastDigit * mul;
mul *= 10;
}
}
return result;
}
答案 2 :(得分:0)
您可以尝试这样做:
int intWithZeros = 1020300; // for example
String intAsString = String.valueOf(intWithZeros); // represent the int as a String
String resultString= "";
for (char digit : intAsString.toCharArray()) { // cycle through every char
if(digit!='0') { // if it is not a zero
resultString+=digit; // append it to the resultString
}
}
if (!resultString.equals("")) {
return Integer.parseInt(resultString);
}
return 0;
<强>输入:强>
1020300
<强>输出:强>
123