检查整数是否包含数字javascript

时间:2019-05-01 00:54:25

标签: javascript

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

例如:

var n = 12;
var m = 34;

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

在不将整数转换为字符串的情况下最快的方式(性能明智)?

4 个答案:

答案 0 :(得分:3)

请参阅以下代码(如果注释不够好,请随时提出):

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;
}

答案 1 :(得分:0)

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

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

答案 2 :(得分:-2)

尝试:

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);

答案 3 :(得分:-3)

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

     /// Do something

}