IN JAVA, Given a positive int n, return true if it contains a 1 digit. Note: use % to get the rightmost digit, and / to discard the rightmost digit.


hasOne(10) â true
hasOne(22) â false
hasOne(220) â false

Respuesta :

Answer:

Here is code in java.

import java.util.*;

class Solution

{

public static void main (String[] args) throws java.lang.Exception

{

   try{

       int n;

        //scanner class object to read input

       Scanner scnr=new Scanner(System.in);

       System.out.print("please enter the number:");

        // read the input from user

       n=scnr.nextInt();

        // call the function with argument n

       System.out.println(hasOne(n));

   

   }catch(Exception ex){

       return;}

}

 // method to find "1" in the input number

public static Boolean hasOne(int num)

{

    int r;

    boolean flag=false;

    r=num%10;

    while(num>0)

     {

        //if remainder is 1 then flag will be true

        if(r==1)

        {

            flag=true;

            break;

        }

         // if the remainder is not '1' then it discard the digit

         num=num/10;

        r=num%10;

       

    }

    // returning the value

    return flag;

}

}

Explanation:

Create a scanner class object "scnr" to read input.Call the function hasOne()

with parameter "n".In the hasOne(),find the remainder and check if it is equal to  1 or not.if it is equal to 1 then set the flag "true" otherwise discard that digit

as "num=num/10".Repeat this until "num>0".This function will return a boolean value base on the presence of "1" in the number.

Output:

please enter the number:10                                                                                                                        

true  

please enter the number:22                                                                                                                        

false  

ACCESS MORE