美文网首页
辅导笔记(5):数字逆序

辅导笔记(5):数字逆序

作者: David_IT | 来源:发表于2018-08-31 23:26 被阅读0次

∥两种方法实现

//输入一个整数,要求反转输出,输出后仍然是具有意义的整数

//输入样例:-30800  900  123

//输出结果: -803  9    321

#include<iostream>

#include<string>

using namespace std;

int main()

{

string str;//字符串方法

cin>>str;

int n=str.length()-1,start;

if(str[0]==str[n]&&str[0]=='0')  //只输入0的情况下,输出0

cout<<'0';

while(str[n]=='0'){  //去掉尾部的'0'

n--;

}

if(str[0]=='-') //如果为负数,start设置为1

{

  cout<<'-';

  start=1;

}

else start=0;  //如果不带符号,start设置为0

while(n>=start) //逆序输出,从n到起点

{

cout<<str[n];

n--;

}

return 0;

}

另一种方法:

#include<iostream>

#include<string>

using namespace std;

int main()

{

int n;// 整数数字分解方法

cin>>n;

bool flag=true;//flag 默认为正整数,flag为假,负数

if(n<0)  {

flag=false;

n=-n;//先当做整数处理

}

while(n%10==0)  n/=10; //去掉整数末尾的所有0

if(!flag) cout<<'-';//输出负号

while(n>0) {  //逆序输出

cout<<n%10;

n/=10;

}

return 0;

}

相关文章

网友评论

      本文标题:辅导笔记(5):数字逆序

      本文链接:https://www.haomeiwen.com/subject/vafywftx.html