stackoverflow错误:检查数字是偶数还是奇数没有%或/运算符 [英] stackoverflow error : check if number is even or odd without % or / operator

查看:127
本文介绍了stackoverflow错误:检查数字是偶数还是奇数没有%或/运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//检查一个数字是偶数还是奇数没有/或%运算符。

// check for a number is even or odd without / or % operator.

public class EvenOrOdd {

    public static int CheckEvenOrOdd(int num) {
        if (num > 2) {
            int number = num - 2;
            num = CheckEvenOrOdd(number);
        }
        return num;
    }

    public static void main(String[] args) {
        int num = CheckEvenOrOdd(5322221);
        if (num == 1) {
            System.out.println("Odd number");
        } else {
            System.out.println("Even number");
        }
    }

}

我已定义堆栈大小为200米-xss200m,但如果数字大于5322221,则此程序出现OutOfMemory错误和StackOverflow错误。

I defined stack size to 200m as -xss200m but this program turn up with OutOfMemory error and StackOverflow error if number is greater then 5322221.

建议如何解决此问题以查找数字是偶数还是奇数。

Advise how to solve this problem to find the number is even or odd.

推荐答案

你可以使用每个奇数都 1 在其二进制表示的末尾,所以它看起来像 ??????? 1 其中可以是0或1.以下是如何使用二进制格式检查它 - > &

You can use a fact that every odd number have 1 at the end of its binary representation so it looks like ???????1 where ? can be either 0 or 1. Here is how you can check it with binary AND -> &

public static boolean isEven(int num) {
    return (num & 1) == 0;
}

它的工作原理如下:

代表奇数

          ????????1 -> any odd number
          000000001 -> one
AND       ---------
result    000000001 -> one

偶数的

for even numbers

          ????????0 -> any even number
          000000001 -> one
AND       ---------
result    000000000 -> zero

这篇关于stackoverflow错误:检查数字是偶数还是奇数没有%或/运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆