我需要将整数的位置反转,例如:
输入 = 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;
}
我需要将整数的位置反转,例如:
输入 = 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;
}
这里是一个解决方案
int num = 12345;
int new_num = 0;
while(num > 0)
{
new_num = new_num*10 + (num % 10);
num = num/10;
}
cout << new_num << endl;
您的循环终止得太早了。请更改
}while(num/i!=0);
}while((num*10)/i!=0);
再进行一次迭代,你的代码就能正常工作了。
如果你作为一个例子尝试一次,你会看到你的错误。
输入: 12
第一次循环:
输出: 12%10 = 2 / 1 = 2
i = 100
测试: 12/100 = 0 (作为整数)
终止时有一个错误。
一个解决方案是测试
(num % i) != num
只是众多解决方案之一。
用以下代码替换您的 while 循环语句
while (i<10*num)
如果我在做这件事,我会(可能)首先创建一个新值作为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());
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;
}
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
cout << (n%10) << (n/10);
return 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;
}
}
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
记住,在 C 语言中,整数除法总是向下取整(或者说是朝零方向取整)。那么如果 num < 10
且 i = 10
,num / i
的值会是多少呢?