Detect if two integers have opposite signs
来源:互联网 发布:属下知罪by枯目腐书 编辑:程序博客网 时间:2024/06/05 20:03
来源: http://www.geeksforgeeks.org/detect-if-two-integers-have-opposite-signs/
不采用算术运算符,我们可以采用以下几种方法。
(1) 首先异或操作可以判断两个数是否是同号的,因为异或运算是将符号位包括在内的,非负数符号位为0,负数符号位为1,所以0^1=1,异或的结果符号位1,即为负数。
#include<stdbool.h>#include<stdio.h> bool oppositeSigns(int x, int y){ return ((x ^ y) < 0);} int main(){ int x = 100, y = -100; if (oppositeSigns(x, y) == true) printf ("Signs are opposite"); else printf ("Signs are not opposite"); return 0;}
(2)可以通过比较运算符
bool oppositeSigns(int x, int y){ return (x < 0)? (y >= 0): (y < 0);}
(3)当int为32位时,我们可以直接采用位运算符而不需要采用比较运算符。
如果异或结果的符号位为0,则将异或结果右移31位后结果为0.
如果异或结果的符号位为1,则将异或结果右移31位后结果的二进制表示全为1,结果为-1(C语言中非0的数即为true),因此我们不难写出以下代码。
bool oppositeSigns(int x, int y){ return ((x ^ y) >> 31);}
争取每天晚上看两篇Geeksforgeeks的文章,这样不出几天,我就可以看完了,哇哈哈哈。。。。
0 0
- Detect if two integers have opposite signs
- Detect if two integers have opposite signs
- Detect whether two rectangles have common area or not -- Amazon
- Compute the maximum of two integers without if-else
- LeetCode: Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode] Divide Two Integers
- Divide Two Integers
- Divide Two Integers
- LeetCode28:Divide Two Integers
- [Leetcode] Divide Two Integers
- LeetCode Divide Two Integers
- Divide Two Integers
- 【leetcode】Divide Two Integers
- Divide Two Integers
- Divide Two Integers
- [LeetCode]Divide Two Integers
- leetcode 刷题, 总结,记录,备忘 35
- 数据结构实验之栈四:括号匹配
- CDN
- 21行Python写出拼写检查器
- LightOJ 1370(欧拉函数)
- Detect if two integers have opposite signs
- 关于actionbar和popupmenu结合的实例
- Objective-c
- 黑马程序员-C语言基础学习心得-02
- 一个循环实现冒泡法排序(并没有什么卵用)
- 变量、数组、集合、泛型的发展
- virtualization--Create Virtual Machine#2
- 费工行截图今天又
- android 倒计时