前言
提示:2020/10/2 在LintCode做的第一道算法题
一、题目及要求
描述
反转一个只有3位数的整数。
样例
样例 1:
输入: number = 123
输出: 321
样例 2:
输入: number = 900
输出: 9
二、思路
在最一开始c++课程中做过关于反转字符的题目,可以直接取个十百...位来反转,也可以通过字符数组来直接输出。
通过举例子可知,如何取出个十百等位上的数。
int a = number/100; // c++中‘/’自动取整,百位
int b = number%100/10;//十位
int c = number%10; //个位
第一次代码如下:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int num;
int a,b,c;
cin>>num;
if (num>100 && num<1000)
{
a = num / 100;
b = num % 100 /10;
c = num % 10;
cout<<c<<b<<a;
}
else
{
cout<<"error";
}
return 0;
}
思路:
由于只考虑到如果取出个十百位,而忽略了第二个例子 900->9。在以前的题目中900都会直接输出009,而这个题目不同,所以我加入了一个if判断来判断b和c是否为0,既可以解决xx0,x00的情况。
改了之后的代码如下:
#include <iostream>
using namespace std;
int main()
{
int num;
int a,b,c;
cin>>num;
if (num>100 && num<1000)
{
a = num / 100;
b = num % 100 /10;
c = num % 10;
if (c == 0)
{
if (b == 0)
{
cout<<a;
}
else
{
cout<<b<<a;
}
}
else
{
cout<<c<<b<<a;
}
}
else
{
cout<<"error";
}
return 0;
}
但还是没办法通过LintCode,通过查资料发现可以更简洁,比如直接int完之后就赋值运算,直接return时用个位*100+十位*10+百位*1就可以完成反转,并且不用消去个十位的0;
代码如下:
class Solution {
public:
/**
* @param number: A 3-digit number.
* @return: Reversed number.
*/
int reverseInteger(int number) {
// write your code here
int a = number/100;
int b = number % 100 /10;
int c = number % 10;
return c*100 + b*10 + a;
}
};
总结
提示:这里对文章进行总结:要习惯用class类这样的方法来写代码,不能一直用#include .......