Learning Algorithms with JS, Python and Java 3: Integer Reversal

I joined dev.to this week and posted two little articles. Thank you for the hearts and unicorns (though I’m still not really sure what unicorns mean)!

The third question in the Stephen Grider’s course is to reverse an integer. I’ll just quote the directions here.

— Directions
Given an integer, return an integer that is the reverse ordering of numbers.
— Examples
reverseInt(15) === 51
reverseInt(981) === 189
reverseInt(500) === 5
reverseInt(-15) === -51
reverseInt(-90) === -9

Stephen’s JS solution is:

function reverseInt(n) {
    const reversed = n
        .toString()
        .split('')
        .reverse()
        .join('');

    return parseInt(reversed) * Math.sign(n);
}

Enter fullscreen mode Exit fullscreen mode

This works because parseInt('12-') returns 12.

A neater solution might be:

function reverseInt(n) {
    const absReversed = Math.abs(n)
        .toString()
        .split('')
        .reverse()
        .join('');

    return Number(absReversed) * Math.sign(n);
}

Enter fullscreen mode Exit fullscreen mode

My attempt in Python:

def reverse_int(n):
    abs_reversed = str(abs(n))[::-1]
    if n > 0:
        return int(abs_reversed)
    else:
        return -int(abs_reversed)

Enter fullscreen mode Exit fullscreen mode

int(’12-‘) throws a ValueError, so abs() cannot be omitted.
I wonder if there’s a cooler way to do it.

And Java:

public static int reverseInt(int n) {
    String abs = Integer.toString(Math.abs(n));
    String absReversed = new StringBuilder(abs).reverse().toString();
    return Integer.parseInt(absReversed) * Integer.signum(n);
}

Enter fullscreen mode Exit fullscreen mode

parseInt('12-') throws a NumberFormatException in Java, so Math.abs() cannot be omitted.

原文链接:Learning Algorithms with JS, Python and Java 3: Integer Reversal

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容