값이 홀수인지 또는 짝수인지 테스트
매우 간단한 알고리즘으로 간단한 isEven 및 isOdd 함수 를 작성하기로 결정했습니다 .
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
n에 특정 매개 변수가 있으면 괜찮지 만 많은 시나리오에서 실패합니다. 그래서 가능한 많은 시나리오에 대해 올바른 결과를 제공하는 강력한 함수를 만들기 위해 노력했습니다. 따라서 자바 스크립트 수 한도 내의 정수 만 테스트하고 다른 모든 것은 false (+ 및-무한대 포함)를 반환합니다. 0은 짝수입니다.
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
누구든지 위의 문제를 볼 수 있습니까? 더 나은 버전이 있습니까 (즉, 난독 화되지 않고 더 정확하고, 빠르거나 간결합니다)?
다른 언어와 관련된 다양한 게시물이 있지만 ECMAScript에 대한 결정적인 버전을 찾을 수 없습니다.
계수 사용 :
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
다음을 사용하여 Javascript의 값을 숫자로 변환 할 수 있는지 확인할 수 있습니다.
Number.isFinite(parseFloat(n))
This check should preferably be done outside the isEven
and isOdd
functions, so you don't have to duplicate error handling in both functions.
I prefer using a bit test:
if(i & 1)
{
// ODD
}
else
{
// EVEN
}
This tests whether the first bit is on which signifies an odd number.
How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)
function isEven(n) {
return /^-?\d*[02468]$/.test(n);
}
function isOdd(n) {
return /^-?\d*[13579]$/.test(n);
}
Note: there are also negative numbers.
function isOddInteger(n)
{
return isInteger(n) && (n % 2 !== 0);
}
where
function isInteger(n)
{
return n === parseInt(n, 10);
}
Why not just do this:
function oddOrEven(num){
if(num % 2 == 0)
return "even";
return "odd";
}
oddOrEven(num);
To complete Robert Brisita's bit test .
if ( ~i & 1 ) {
// Even
}
var isEven = function(number) {
// Your code goes here!
if (number % 2 == 0){
return(true);
}
else{
return(false);
}
};
A simple modification/improvement of Steve Mayne answer!
function isEvenOrOdd(n){
if(n === parseFloat(n)){
return isNumber(n) && (n % 2 == 0);
}
return false;
}
Note: Returns false if invalid!
We just need one line of code for this!
Here a newer and alternative way to do this, using the new ES6 syntax for JS functions, and the one-line syntax for the if-else
statement call:
const isEven = num => ((num % 2) == 0) ? true : false;
alert(isEven(8)); //true
alert(isEven(9)); //false
alert(isEven(-8)); //true
Different way:
var isEven = function(number) {
// Your code goes here!
if (((number/2) - Math.floor(number/2)) === 0) {return true;} else {return false;};
};
isEven(69)
Otherway using strings because why not
function isEven(__num){
return String(__num/2).indexOf('.') === -1;
}
if (testNum == 0);
else if (testNum % 2 == 0);
else if ((testNum % 2) != 0 );
To test whether or not you have a odd or even number, this also works.
const comapare = x => integer(checkNumber(x));
function checkNumber (x) {
if (x % 2 == 0) {
return true;
}
else if (x % 2 != 0) {
return false;
}
}
function integer (x) {
if (x) {
console.log('even');
}
else {
console.log('odd');
}
}
Using modern javascript style:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = n=> isOdd(+n+1)
Maybe this? if(ourNumber % 2 !== 0)
Simple way to test whether a number is even using JavaScript
function isEven(x) {
//return true if even
if (x % 2 === 0) {
return true;
}
//return false otherwise
else {
return false
}
}
// or much simpler
function isEven(x) {
return x % 2 === 0;
}
This one is more simple!
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);
function isEven(n) {return parseInt(n)%2===0?true:parseInt(n)===0?true:false}
when 0/even wanted but
isEven(0) //true
isEven(1) //false
isEven(2) //true
isEven(142856) //true
isEven(142856.142857)//true
isEven(142857.1457)//false
if (i % 2) {
return odd numbers
}
if (i % 2 - 1) {
return even numbers
}
참고URL : https://stackoverflow.com/questions/6211613/testing-whether-a-value-is-odd-or-even
'Programing' 카테고리의 다른 글
'--color'및 '--format specdoc'옵션을 유지하도록 RSpec을 전역 적으로 구성하는 방법 (0) | 2020.06.07 |
---|---|
친숙한 URL을위한 안전한 문자 (0) | 2020.06.07 |
WebView에서 파일 업로드 (0) | 2020.06.07 |
Java : System.console ()에서 입력을 얻는 방법 (0) | 2020.06.07 |
안드로이드 소프트 키보드 커버 편집 텍스트 필드 (0) | 2020.06.07 |