颠倒整数数字的位置?

6

我需要将整数的位置反转,例如:

输入 = 12345

输出 = 54321

我已经尝试过以下代码,但是输出结果不正确(例如输出为5432):

#include <iostream>
using namespace std;

int main(){
 int num,i=10;   
 cin>>num;   

 do{
    cout<< (num%i)/ (i/10);
    i *=10;
   }while(num/i!=0);

 return 0;
}

你必须将值处理为整数,还是可以将它们处理为字符串或字符数组? - Thomas Owens
只能使用循环或选择结构,不能使用除整数以外的任何内容。 - bbjkdsfj
SO上已经有很多重复的问题了(似乎是每年都会出现的作业问题)- 例如,请参阅c program for the reverse the digits - Paul R
13个回答

12

这里是一个解决方案

    int num = 12345;
    int new_num = 0;
    while(num > 0)
    {
            new_num = new_num*10 + (num % 10);
            num = num/10;
    }
    cout << new_num << endl;

10

您的循环终止得太早了。请更改

}while(num/i!=0);
}while((num*10)/i!=0);

再进行一次迭代,你的代码就能正常工作了。


2

如果你作为一个例子尝试一次,你会看到你的错误。

输入: 12

第一次循环:

输出: 12%10 = 2 / 1 = 2
i = 100
测试: 12/100 = 0 (作为整数)

终止时有一个错误。

一个解决方案是测试

(num % i) != num

只是众多解决方案之一。


0

用以下代码替换您的 while 循环语句

while (i<10*num)

0

如果我在做这件事,我会(可能)首先创建一个新值作为int,然后打印出该值。我认为这应该可以简化代码。作为伪代码,它看起来应该是这样的:

output = 0;

while (input !=0)
    output *= 10
    output += input % 10
    input /= 10
}
print output

另一种明显的可能性是首先将其转换为字符串,然后反向打印该字符串:
std::stringstream buffer;

buffer << input;

cout << std::string(buffer.str().rbegin(), buffer.str().rend());

0
int _tmain(int argc, _TCHAR* argv[])
{
int x = 1234;
int out = 0;
while (x != 0)
{
    int Res = x % (10 );
    x /= 10;
    out *= 10;
    out +=  Res;
}
cout << out;


} 

0
以下代码仅适用于两位数。
#include<iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    cout << (n%10) << (n/10);    
return 0;
}

这个问题很老了,已经有很多回答适用于比2位数更一般的情况。为什么你的答案更好? - Wai Ha Lee

0
int a,b,c,d=0;
cout<<"plz enter the number"<<endl;
cin>>a;
b=a;
do
{
    c=a%10;
    d=(d*10)+c; 
    a=a/10;
}
while(a!=0);
cout<<"The reverse of the number"<<d<<endl;
if(b==d)
{
    cout<<"The entered number is palindom"<<endl;
}
else
{
    cout<<"The entered number is not palindom"<<endl;
}

}


请添加您提出的解决方案的描述。 - il_raffa

0
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;
}

这将反转任何有符号或无符号整数(short、byte、int、long...)中的位。您可以提供额外的参数nBits来在反转时框定位。

例如: 8位中的7 = 00000111 -> 11100000 4位中的7 = 0111 -> 1110


0

记住,在 C 语言中,整数除法总是向下取整(或者说是朝零方向取整)。那么如果 num < 10i = 10num / i 的值会是多少呢?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接