[解题报告] 《C语言入门100例》(第11例) 溢出

 零、写在前面

        这个系列不经常更新,今天这个题目又双叒叕觉得有点意思,我们一起看一看,主要知识点在

【第11题】给出四个数,输出四个数的和 | 溢出了怎么办?icon-default.png?t=LA92https://blog.csdn.net/WhereIsHeroFrom/article/details/118237457

一、主要知识点

        1.溢出处理

        由于数据的量级只有\left [ 0,2^{62} \right ],所以只有四个数字都是最大的时候才会产生溢出

#include <stdio.h>
typedef unsigned long long ull;                           //换名
const ull MAX = (((ull)1)<<62);                           //需要对1进行类型转换

int main() {
	int t;
	ull a, b, c, d;
	scanf("%d", &t);
	while (t--) {
		scanf("%llu %llu %llu %llu", &a, &b, &c, &d);     // 读入数据
		if (a == MAX && b == MAX && c == MAX && d == MAX) // 判断溢出条件
			printf("18446744073709551616\n");             // 溢出的值只能用字符串
		else
			printf("%llu\n", a + b + c + d);              // 非溢出直接返回
	}
	return 0;
}

        2.异或运算

        这个曾经写过 参考这里的知识点

[解题报告]《算法零基础100讲》(第16讲) 变量交换算法icon-default.png?t=LA92https://blog.csdn.net/qq_17593855/article/details/121156818


二、课后习题 

   476. 数字的补数

476. 数字的补数icon-default.png?t=LA92https://leetcode-cn.com/problems/number-complement/思考

扫描所有位取反就好了,利用上面的异或方法,一个数字对1取异或就可以得到这个数字的取反。

int findComplement(int num){
    for(int i = 0;num >> i;i++)//扫描所有位取反
        num = num ^ (1 << i);
    return num;
}

结果分析

凑合玩


7. 整数反转

7. 整数反转icon-default.png?t=LA92https://leetcode-cn.com/problems/reverse-integer/

思考

按照要求进行返回就好了,但是在反转过程中要注意有没有超出限制,一开始都用负数处理,因为负数的表示范围大。

int reverse(int x){
    int ans = 0;bool flag = false;
    int min_int = -2147483648;
    if(x > 0){      //符号处理
        x = -x;
        flag = true;
    }
    for(int i = 0;x;++i){   //处理最终结果
        if(ans < min_int / 10) return 0;//溢出
        ans *= 10;
        if(ans < min_int - (x%10)) return 0;//溢出
        ans += (x%10);
        x /= 10;
    }
    if(flag && ans == min_int) return 0;
    if(flag)    ans = -ans;
    return ans;
}

结果分析

还行哈?


写在最后

这个系列确实是不怎么更新,今天这两道题需要注意的细节比较多,并且位运算比较有意思,所以还是建立一个合集,有需要的欢迎关注。

猜你喜欢

转载自blog.csdn.net/qq_17593855/article/details/121285859