逆转数字的最有效方法 [英] The most efficient way to reverse a number

查看:116
本文介绍了逆转数字的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种有效的算法来反转数字,例如

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

输入: 3456789

输出: 9876543

在C ++中,有很多带有移位和位掩码的选项,但是最有效的方法是什么?

In C++ there are plenty of options with shifting and bit masks but what would be the most efficient way ?

我的平台:x86_64

My platform: x86_64

数字范围:XXX-XXXXXXXXXX(3-9位数字)

Numbers range: XXX - XXXXXXXXXX (3 - 9 digits)

编辑 我输入的最后一位永远不会是零,所以没有前导零的问题.

EDIT Last digit of my input will never be a zero so there is no leading zeros problem.

推荐答案

类似的方法将起作用:

#include <iostream>

int main()
{
    long in = 3456789;
    long out = 0;
    while(in)
    {
        out *= 10;
        out += in % 10;
        in /= 10;
    }
    std::cout << out << std::endl;
    return 0;
}

这篇关于逆转数字的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆