NYOJ-1071解题报告 不可以

来源:互联网 发布:倚天屠龙记结局知乎 编辑:程序博客网 时间:2024/05/16 00:56

不可以!

时间限制:1000 ms  |  内存限制:65535 KB
难度:1
描述

判断:两个数x、y的正负性。

要求:不可以使用比较运算符,即"<",">","<=",">=","==","!="

输入
有多组数据,每组数据占一行,每一行两个数x,y。
x、y保证在int范围内。
输出
每组数据输出占一行。
如果两个数是一正一负,输出"Signs are opposite"
如果是同为正或同为负,输出"Signs are not opposot"
如果无法确定,输出"Signs can't be sure"
输出不包括引号
样例输入
1 1-1 1
样例输出
Signs are not opposotSigns are opposite


不让用判断符号。

我的思路是利用int类型数的存储特点,在计算机中int类型的数是以补码形式存储的,比如-1  的存储是ff ff ff ff首位为符号位1,1的存储是00 00 00 01 ,对于0有唯一的存储就是00 00 00 00 然后就可以判断了。





package NYoj;import java.util.Scanner;public class _1071 {static int state(int a){//正数返回1,负数-1,0返回0char[] tmp = Integer.toBinaryString(a).toCharArray();try{int aa = tmp[31];if((tmp[0]+"").contains("1"))return -1;elsereturn 1;}catch(ArrayIndexOutOfBoundsException e){//因为正数前面无意义的0会被省略,所以<span style="white-space:pre"></span>//tmp[31]会报错,要利用异常还处理try{int aa = tmp[1];return 1;}catch(ArrayIndexOutOfBoundsException ee){if((tmp[0]+"").contains("1"))return 1;elsereturn 0;}}}public static void main(String[] args) {Scanner sc = new Scanner(System.in);while(sc.hasNext()){int a = sc.nextInt();int b = sc.nextInt();if( new Integer(state(a)).equals(0) || new Integer(state(b)).equals(0)){//这里<span style="white-space:pre"></span>//其实也是用了等号,只是没有显式的使用System.out.println("Signs can't be sure");}else if( !new Integer(state(a)*state(b)).equals(-1) ){System.out.println("Signs are not opposot");}else{System.out.println("Signs are opposite");}}}}



其实我觉得我的方法也是很不好的,感觉仅仅是可以做题而已没有什么实际的意义,太繁杂,有兴趣可以讨论下。

0 0
原创粉丝点击