reverse the position of integer digits?

后端 未结 13 2512
予麋鹿
予麋鹿 2021-02-09 15:00

i have to reverse the position of integer like this

input = 12345

output = 54321

i made this but it gives wrong output e.g 5432

#include         


        
相关标签:
13条回答
  • 2021-02-09 15:38
    template <typename T>
    T reverse(T n, size_t nBits = sizeof(T) * 8)
    {
        T reverse = 0;
        auto mask = 1;
    
        for (auto i = 0; i < nBits; ++i)
        {
            if (n & mask)
            {
                reverse |= (1 << (nBits - i - 1));
            }
            mask <<= 1;
        }
    
        return reverse;
    }
    

    This will reverse bits in any signed or unsigned integer (short, byte, int, long ...). You can provide additional parameter nBits to frame the bits while reversing.

    i. e. 7 in 8 bit = 00000111 -> 11100000 7 in 4 bit = 0111 -> 1110

    0 讨论(0)
提交回复
热议问题