简体   繁体   English

如何控制从 long 到 int 的隐式转换?

[英]How to control implicit conversion from long to int?

I am working on this LeetCode problem to take an integer and reverse it, given that the reversed in is within the signed 32-bit range, in which case we should return 0.我正在研究这个 LeetCode 问题,取一个 integer 并将其反转,假设反转的 in 在带符号的 32 位范围内,在这种情况下我们应该返回 0。

and this code is doing just that, even with numbers like 1534236469/-1534236469.这段代码就是这样做的,即使是像 1534236469/-1534236469 这样的数字。 Except when it comes to tricky numbers like -2147483648 where its not recognising it as out of range and instead returning 8 and not 0.除了遇到像 -2147483648 这样棘手的数字时,它不会将其识别为超出范围,而是返回 8 而不是 0。

I know this is not the cleanest code, but can you help me recognise what I'm missing?我知道这不是最干净的代码,但你能帮我认清我遗漏了什么吗?

#include<iostream>
#include<limits>
using namespace std;

class Solution {
public:
    int reverse(int x) {
        int a, r, y;
        string num, fnum;
        a = abs(x);
        try{
            while(a != 0){
                r = a % 10;
                a = a / 10;
                num = to_string(r);
                fnum = fnum + num;
                y = stoi(fnum);
            }
        } catch(out_of_range& oor){
            return 0;
        }
        if(x==0){
            return 0;
        } else if (x<0){
            return -y;
        } else {
            return y;
        }
    }
};

int main(){
    Solution mine;
    cout << mine.reverse(-2147483648);
}

[...] when it comes to tricky numbers like -2147483648 where its not recognising it as out of range and instead returning 8 and not 0. [...] 当涉及到像 -2147483648 这样棘手的数字时,它不会将其识别为超出范围,而是返回 8 而不是 0。

That number is "tricky" because it's equal to std::numeric_limits<int>::min() in your environment and given a two's complement representation of type int , it happens that std::abs(-2147483648) == -2147483648 .这个数字是“棘手的”,因为它在您的环境中等于std::numeric_limits<int>::min()并且给定类型int的二进制补码表示,碰巧std::abs(-2147483648) == -2147483648 .

Next in your (contrived, I must say, there's no need to use a string here) code, the line num = to_string(r);接下来在您的代码中(做作,我必须说,这里不需要使用字符串),行num = to_string(r); would result in num = "-8" , so that the loop would compose a string like "-8-4-6-3-8-4-7-4-1-2" .将导致num = "-8" ,因此循环将组成一个字符串,如"-8-4-6-3-8-4-7-4-1-2"

When applyed to strings like that, stoi doesn't throw an exception, it just stops parsing (you would have noticed it by passing and inspecting its other parameters).当应用于这样的字符串时, stoi不会抛出异常,它只是停止解析(您会通过传递和检查它的其他参数来注意到它)。

If you want to check if the result is outside the range of an int , you could use locally a wider type (eg long long ) and check the boundaries after the calculations or keep using int , but compare all the intermediate values with the limits before any calculation.如果你想检查结果是否超出int的范围,你可以在本地使用更宽的类型(例如long long )并在计算检查边界或继续使用int ,但将所有中间值与之前的限制进行比较任何计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM