简体   繁体   中英

How to remove trailing zeros from an integer (ex: 300 => 3, 4 => 4, 5000 => 5, 6060 => 606?

The question speaks for itself. How can I do this transformation for any integer number?

300 => 3
4 => 4
5000 => 5
6060 => 606
0 => 0
77 => 77

You need to divide the number by 10, as long as it is divisible by 10.

This would be an implementation. A number is divisible by 10 if number % 10 == 0 . We also need to check if the number is number != 0 to handle the case where the input number would be 0.

private static int stripTrailingZeros(int number) {
    while (number != 0 && number % 10 == 0) {
        number /= 10;
    }
    return number;
}

Can be achieved using a recursive function and the modulus operator.

public static int recursiveZeroStripper(int numberWithTrailingZero) {
    if(numberWithTrailingZero == 0){
        return numberWithTrailingZero;
    }
    if(numberWithTrailingZero%10==0){
        return recursiveZeroStripper(numberWithTrailingZero/10);
    }
    return numberWithTrailingZero;
}

Ran that function with

    int num=-100;
    System.out.println(recursiveZeroStripper(num));

Which resulted in the output of

-1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM