Optimizing adding zero padding in a number

Uzi :

I'm practicing on how to optimize codes so any suggestion would be much appreciated. I have this method that adds zero padding to a number when its being incremented. The code are as follows:

public class CommonAlgorithm {

    NumberRetrieve retrieve;

    public long incrementNumber(CommonNumber t) {
        CommonNumberFacade facade = new CommonNumberFacade(retrieve.apply(t));
        String number = facade.getGeneratedNumber();

        Long num = Long.parseLong(number);
        num++;

        String result = "";
        if (String.valueOf(num).length() < number.length()) {
            int length = number.length() - String.valueOf(num).length();
            String zero = "";
            for (int i = 0; i < length; i++) {
                zero += "0";
            }

            result = zero + num;
        } else {
            result = String.valueOf(num);
        }

        return Long.parseLong(t.getPrefix()+result);
    }
}

Are there more ways to optimize the code above?

Just in case anyone asks for the purpose of the function, the premise goes like this:

The function returns a number that is composed of the following: a 'prefix' and a 'number'. These two are concatenated to each other after the number has been incremented by 1. However, I realized that if the value of the number has zero padding in it, those zeroes will be disappear once they are converted into a long data type. Therefore if the following values are applied:

prefix = 123
number = 000001

The return value will be 1232 instead of 123000002. That is the problem that the function above is solving. I can't change the return type of the facade.generatedNumber() function into long as I need to return that String return type somewhere in my project eventually. I hope you could give a couple of suggestions

Eran :

You can simplify your if-else statement as follows:

StringBuilder sb = new StringBulder();
String numStr = String.valueOf(num);
for (int i = numStr.length(); i < number.length(); i++) {
    sb.append('0');
}
sb.append(numStr);
String result = sb.toString();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87099&siteId=1