0

How to write code in JS,for check if a given digit contains in other given number?

23rd Feb 2020, 2:33 PM
Григорий Бондарев
Григорий Бондарев - avatar
4 Respostas
+ 2
If number is not provided as string convert it to string. you can use String() or toString() methods let n = 56; n = String(n); OR n = n.toString(); probably much simpler but not good for readability , you can concat number with an empty string. n = n + ''; once you have converted number to string use includes() method. let digit = 5; //not necessary to be of type string. n.includes(digit); // true
23rd Feb 2020, 2:49 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
here is a primitive way of doing it : var digit = 6; var num = 12365; for( var i = 0; i < num.toString().length ;i++){ if(digit == num.toString()[i] ){ console.log("found at index " + i); } }
23rd Feb 2020, 2:54 PM
Bahhaⵣ
Bahhaⵣ - avatar
0
Have you tried it yourself yet? We unfortunately can't help you until you've tried it, so you can learn programming. I can give you a couple of hints though: 📍Take two inputs(number and digit), both numbers. Don't convert them to integers though, as it will make comparing easier. 📍Create a for loop to go through each of the characters in the first input. We can use length, which gets the length of a string: for (var character = 0; character < given_number.length; character++) { //your code goes here } 📍Finally, get the character at that part in the given number and compare it to the second input: if (given_number[character] == digit) //checks if character at given index is equal to digit { //your code goes here }
23rd Feb 2020, 2:39 PM
Jianmin Chen
Jianmin Chen - avatar
0
I wrote something like that... let digit = 5; let number = 2463; for(; number >0; number % 10){ if(number % 10 === digit){ console.log("yes") }else { number = Math.floor(number / 10); }else { console.log("no"); } }
23rd Feb 2020, 2:45 PM
Григорий Бондарев
Григорий Бондарев - avatar