LintCode 37. 反转一个3位整数

前言

提示: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 .......
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值