Best Way to Check if a Number Contains Another Number Need to find out if a number contains another number? And you want better performance than converting to a string and then looping through that to find the key number? Well you’ve come to the right place!
Using a combination of the modulo operator and division it’s possible to pull the number apart one digit at a time until it reaches 0.
Implementation Using a Loop def checkNumberIfContainsKey (number, key):
while number > 0 :
if number % 10 == key:
return True
number = number // 10
return False
package main
import "fmt"
func checkNumberIfContainsKey (number , key int ) bool {
for number > 0 {
if number % 10 == key {
return true
}
number = number / 10
}
return false
}
func main () {
fmt .Println (checkNumberIfContainsKey (359 , 9 ))
}
function checkNumberIfContainsKey (number , key ){
while (number > 0 ){
if (number % 10 == key ){
return true ;
}
number = Math.floor (number / 10 );
}
return false ;
}
#include "bits/stdc++.h"
using namespace std;
bool checkNumberIfContainsKey (int number, int key)
{
while (number > 0 )
{
if (number % 10 == key)
{
return true;
}
number = number / 10 ;
}
return false;
}
int main (int argc, char const * argv[])
{
cout << checkNumberIfContainsKey(359 ,9 ) << endl;
return 0 ;
}
class ContainsKey {
public static boolean checkNumberIfContainsKey (int num, int key) {
while (num > 0) {
if (num % 10 == key) {
return true ;
}
num = num / 10;
}
return false ;
}
}
Recursive Implementation def checkNumberIfContainsKey (number, key):
if number == 0 :
return False
if number % 10 == key:
return True
return checkNumberIfContainsKey(number // 10 , key)
package main
import "fmt"
func checkNumberIfContainsKey (number , key int ) bool {
if number == 0 {
return false
}
if number % 10 == key {
return true
}
return checkNumberIfContainsKey (number / 10 , key )
}
func main () {
fmt .Println (checkNumberIfContainsKey (359 , 9 ))
}
function checkNumberIfContainsKey (number , key ){
if (number === 0 ) {
return false ;
}
if (number % 10 == key ) {
return true ;
}
return checkNumberIfContainsKey (Math.floor (number / 10 ), key );
}
#include "bits/stdc++.h"
using namespace std;
bool checkNumberIfContainsKey (int number, int key)
{
while (number > 0 )
{
if (number % 10 == key)
{
return true;
}
number = number / 10 ;
}
return false;
}
int main (int argc, char const * argv[])
{
cout << checkNumberIfContainsKey(359 ,9 ) << endl;
return 0 ;
}
class ContainsKey {
public static boolean checkNumberIfContainsKey (int num, int key) {
if (num == 0) {
return false ;
}
if (num % 10 == key) {
return true ;
}
return checkNumberIfContainsKey(num / 10, key);
}
}