The most efficient way to reverse a number

后端 未结 10 842

I am looking for an efficient algorithm to reverse a number, e.g.

Input: 3456789

Output: 9876543

In C++ there are p

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-13 05:13

    static public int getReverseInt(int value) {
        int resultNumber = 0;
        for (int i = value; i != 0;) {
            int d = i / 10;
            resultNumber = (resultNumber - d) * 10 + i;
            i = d;
        }
        return resultNumber;
    }
    

    I think this will be the fastest possible method without using asm. Note that d*10 + i is equivalent to i%10 but much faster since modulo is around 10 times slower than multiplication.
    I tested it and it is about 25 % faster than other answers.

提交回复
热议问题