简体   繁体   中英

Keep leading Zeros when subtracting

I would like to know how to keep leading 0s when subtracting numbers, specifically two longs.

Lets say 1000 - 0999 = 0001

I want to keep the answer as a long as well. So just adding the 0s in the front isnt going to work.

Any thoughts?

This is a printing problem:

long n = 1000 - 999;
String s = String.format("%04d", n);  // 0001

More info: Formatter

Leading zeroes are just punctuation. The whole concept applies only to a string that is supposed to represent the number. In fact, until you produce such a string, even the concept of "digit" is meaningless.

So your real question isn't "How do I keep leading zeroes when subtracting?", but rather "How do I get leading zeroes when formatting my result as a string?"

So, for example, to print a number using (at least) 4 digits, with leading zeroes, you might use out.printf("%04d", theNumber) . Or use the same format specifier when creating a string.

As @Sotirios Delimanolis mentioned, you can't do this with longs. You will need to use a string, because longs can't store extra zeros in the front. Try this:

public String subtractWithZeros(long number1, long number2){
    long result = number1 - number2;
    String strResult = String.valueOf(result);
    String strNum1 = String.valueOf(number1);
    String strNum2 = String.valueOf(number2);
    int totalLength = Math.max(strNum1.length(), strNum2.length());
    int numOfNeededZeros = totalLength - strResult.length();
    for(int i = 0;i<numOfNeededZeros;i++){
        strResult = "0" + strResult;
    }
    return strResult;
}

This should return a long with the zeros you wanted at the front. I am assuming the result of subtraction will never be negative.

While this is not the contemporary answer for this [common] question, it is a way to manipulate the "printf" and "format" parameters.

int number = 5_000;

int length = Integer.toString(number).length();

number -= 4_999;

System.out.printf("%0" + length + "d", number);

// result :  0001

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