检查整数是否包含数字javascript

dojqjjoe  于 2022-11-27  发布在  Java
关注(0)|答案(5)|浏览(106)

如何检查整数是否包含数字?
例如:

var n = 12;
var m = 34;

n contains 1 // true
m contains 1 // false

在不将整数转换为字符串的情况下,最快(性能方面)的方法是什么?

t3psigkw

t3psigkw1#

请参考以下代码(如果注解不够好,请随时询问):

function contains(number, digit) {
    if (number < 0) { // make sure negatives are dealt with properly, alternatively replace this if statement with number = Math.abs(number)
        number *= -1;
    }
    if (number == digit) { // this is to deal with the number=0, digit=0 edge case
        return true;
    }
    while (number != 0) { // stop once all digits are cut off
        if (number % 10 == digit) { // check if the last digit matches
            return true;
        }
        number = Math.floor(number / 10); // cut off the last digit
    }
    return false;
}
d5vmydt9

d5vmydt92#

这是一个简单的递归形式-

const contains = (q, p) =>
  p < 10
    ? p === q
    : p % 10 === q || contains(q, p / 10 >>> 0)
    
console.log(contains(1, 12)) // true
console.log(contains(1, 34)) // false
console.log(contains(9, 14293)) // true
console.log(contains(9, 1212560283)) // false
pokxtpni

pokxtpni3#

试试这个。

let num = 487;
let digit = 4;
let flag = false;
while(num>0){
    if(num%10==digit){
        flag = true
        break
    }
        num = (num - (num % 10)) / 10
}
console.log(flag)
vxbzzdmp

vxbzzdmp4#

试试这个:

let n = 1234;
let flag = false;
while (n > 0){
    r = n % 10;
    if(r == 1){
        flag = true;
        break;
    }
    n = (n - (n % 10)) / 10;
}
console.log("n contains 1 = "+flag);
bwleehnv

bwleehnv5#

if (n.toString().includes("1")) {

     /// Do something

}

相关问题