如何在不使用字符串的情况下确定输入的整数是否包含某些数字 [英] How to determine if an inputted integer contains certain digits without using strings

查看:61
本文介绍了如何在不使用字符串的情况下确定输入的整数是否包含某些数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此程序中,我应该确定用户输入的整数是否包含某个数字(在本例中为7和3),然后返回一个布尔值.到目前为止,我有:

In this program I am supposed to figure out if the integer that the user enters contains a certain digit (in this case 7 and 3), and then return a boolean. So far I have:

public static boolean contains(int num, int x) {
    Scanner input = new Scanner(System.in);
    int currentLength = numberDigits(num); //method that counts the number of digits in the inputed integer

    int digit;   // current first digit

    int firstNumber = firstNum(num);
    boolean digitTrue = false;   

    while (currentLength > 0 ) {
        digit = firstNumber;
        if (num == x)
        {
            digitTrue= true;
        } else {
            digitTrue= false;
        }
    }
    return digitTrue;
}

推荐答案

解决这个问题的最好方法是使用%.%或Modulus返回一个数字的余数/一个数字的余数.例如5%2 = 1或355%10 =5.如果您只想检查一个大数字是否为一位数字,我建议使用此方法

The best way to solve this that I know of is to use %. % or Modulus returns the remainder of one number / by another number. For example 5 % 2 = 1 or 355 % 10 = 5. If you are looking only to check a large number for single digit numbers I would suggest this method

public static boolean contains(int num, int x){

while(num >= 0){
    if (num % 10 == x){
        return true;
    }
    if (num > 0){
        num = num / 10;
    }else{
        return false;
    }
}
return false;
}

希望这会有所帮助

这篇关于如何在不使用字符串的情况下确定输入的整数是否包含某些数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆