2017华为暑期实习生招聘真题(3月24日)

昨天做了一下华为的机考题,难度比之前的有所增加,因为涉及的知识不再是众所周知的东西了。

首先第一题就开始坑(对没看过机考经验的人来说)

第一题的题目要求是输入两个整数a,b(0 < a < b <= 70000),求反转后的数字的和。

例如:

输入 123,456

输出 321 + 654 = 975


输入 100,200

输出 3


这道题首先需要处理的就是将int数字反转的问题。这一步可以通过mod 10运算和整除10运算来实现。

关键是输入格式中,两个数字之间是以逗号分割的,所以读入的时候可能需要借助字符串或者流操作,我就是因为没把这个逗号放在心上导致各种出错。


实现如下:

#include <iostream>
#include <malloc.h>
#include <memory.h>
#include <algorithm>
#include <sstream>
#include <cmath>
#include <string.h>
#include <stdlib.h>
#include <cstdlib>

using namespace std;

int Reverse(int x)
{
    stringstream ss;
    string num;
    ss << x;
    ss >> num;
    int sign = x/abs(x);
    int rev = 0;
    for(int i = 0; i < num.length(); i++){
        rev += (num[i] - '0')*pow(10,i);
    }
    /* 当需要反转的数字大于2位时,反转后的数字就会比实际数字少1
       比如123 ——> 320 求解答原因
    */
    if(rev > 99)
        rev = rev+1;

    return rev*sign;
}

int reverseAdd(int a, int b)
{
    if(a < 1 || a > 70000 || b < 1 || b > 70000)
        return -1;
    else{
        return Reverse(a) + Reverse(b);
    }
}

int main()
{
    string member;
    int a, b;
    char comma;
    stringstream ss;
    while(getline(cin, member)){
        ss << member;
        ss >> a >> comma >> b;
        //cout << Reverse(a) << " " << Reverse(b) << " ";
        cout << reverseAdd(a, b) << endl;
    }

}
实际上sign这个变量(正负号)在这道题中不需要,因为根本不需要考虑小于1的情况。

也有使用while来解的方法,但是这样写比较方便,就没管了。

比较好奇的是当数字位数大于2时,这种方法反转后的数字会比实际答案要少1,尚不清楚时什么原因,请各位看官赐教。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值