简体   繁体   English

如何检查一个数字是否包含某个数字?

[英]How to check if a number contains a certain digit?

I need to write a boolean method called hasEight() , which takes an int as input and returns true if the number contains the digit 8 (eg, 18, 808).我需要编写一个名为hasEight()的布尔方法,它接受一个int作为输入,如果数字包含数字 8(例如hasEight() ,则返回 true。

I don't want to use the "String conversion method".我不想使用“字符串转换方法”。

I've tried the below code, but that only checks for the last digit.我试过下面的代码,但只检查最后一位数字。

import java.util.Scanner;

public class Verificare {

    public static boolean hasEight(int numarVerificat) {
        int rest = numarVerificat % 10;
        return rest == 8;
    } 

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Introduceti numarul pentru verificare: ");
        int numar = keyboard.nextInt();
        Verificare.hasEight(numar);
        System.out.println("Afirmatia este: " + Verificare.hasEight(numar));
    
        keyboard.close();
    }
}

If you don't want to use string conversion methods then i think this method can be used.如果您不想使用字符串转换方法,那么我认为可以使用此方法。

public bool hasEight(int number)
{
      while(number > 0)
      {
          if(number % 10 == 8)
              return true;

          number=number/10;
      }
      return false; 
} 

Use the below function.使用以下功能。

boolean hasEight(int num) {
    int rem;
    while (num > 0) {
        rem = num % 10;
        if (rem == 8)
            return true;
        num = num / 10;
    }
    return false;
}

In every iteration of the loop, last digit of the number is retrieved (remainder when divided by 10).在循环的每次迭代中,检索数字的最后一位(除以 10 时的余数)。 If it is 8, true is returned.如果是 8,则返回true Else, number is divided by 10 (integer division so that last digit is removed) and another iteration is started.否则,数字除以 10(整数除法以便删除最后一位数字)并开始另一个迭代。 When all digits are checked (8 or not), number becomes 0 and loop stops.当所有数字都被检查(8 或不是)时,数字变为 0 并且循环停止。

    public static boolean hasEight(int numarVerificat)
    {
        while(numarVerificat > 0)
          {
              if(numarVerificat % 10 == 8)
                  break;
              numarVerificat=numarVerificat/10;
          }
          return (numarVerificat>0); 
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM