RUVIDEO
Поделитесь видео 🙏

Java Puzzle : E01 - Odditiy Problem

Hello friends, welcome to java puzzle, In this video we will discuss about the Oddity problem. This is a simple one question asked by interviewer.

Find the given number is even or odd.

This is the code snippet for given problem. Can you guess this is a correct logic to find the even and odd?

Lets get started with this video title Java Puzzle Episode 01 : Oddity Problem (intro with title)

An odd number can be defined as an integer that is divisible by 2 with a remainder of 1. The expression i%2 computes the remainder when i is divided by 2, so it would seem that this program ought to work.

Unfortunately, it doesn’t; it returns the wrong answer half of the time.

Because half of all int values are negative, and the isOdd method fails for all negative odd values. It returns false when invoked on any negative value, whether even or odd.

According to Java Docs 15.17.2 and 15.17.3, when the remainder operation returns a nonzero result, it has the same sign as its left operand.

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html

When i is a negative odd number, i%2 is equal to -1 rather than 1, so the
isOdd method incorrectly returns false. To prevent this sort of surprise, test that your methods behave properly when passed negative, zero, and positive values for each numerical parameter.

There is two possible solution, first one is simply compare i%2 to 0 rather than to 1, and reverse the sense of the comparison:

Problem with this solution if you are using the isOdd method in a performance-critical setting.

Second option would be better off using the bitwise AND operator (&) in place of the remainder operator.

The second version may run much faster than the first, depending on what
platform and virtual machine you are using, and is unlikely to run slower. As a general rule, the divide and remainder operations are slow compared to other arithmetic and logical operations. It’s a bad idea to optimize prematurely, but in this case, the faster version is as clear as the original, so there is no reason to prefer the original.

SUMMARY:
In summary, Think about the signs of the operands and of the result whenever
you use the remainder operator. The behavior of this operator is obvious when its operands are nonnegative, but it isn’t so obvious when one or both operands are negative.

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Java Puzzle : E01 - Odditiy Problem», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.