Question:
How to check if a number is divisible by 8 using Java

Summary

Here we have defined a class Solution and its DivisibleByEight method, which returns an integer when given a string s as input. 


Solution

//User function Template for Java


class Solution{

    int DivisibleByEight(String s){

        //code here

        if(s.length()>3)

       {

           String temp=s.substring(s.length()-3);

           

               int ans=Integer.parseInt(temp);

               if(ans%8==0)

               {

                   return 1;

               }

               else{

                   return -1;

               }

           

       }

       else{

           int a=Integer.parseInt(s);

           if(a%8==0)

           {

               return 1;

           }

           else{

               return -1;

           }

       }

    }

}


Explanation

  • The DivisibleByEight method determines whether the supplied string, s, represents a number that can be divided by eight.

  • It uses the substring method to extract the final three characters from the string and converts them to an integer if the length of the string s is greater than 3.

  • Next, it determines if this number is divisible by eight. The method returns 1 if it is; -1 if it isn't.

  • It immediately converts the string to an integer and runs the same divisibility check if the length of the string s is not greater than 3.


Suggested blogs:

>Calculating the Nth Fibonacci Number

>How to clone an undirected graph using Java

>Check if strings are rotations of each other or not with Java

>How to Detect cycle in an undirected graph with Java?

>How to check whether all leaves are at the same level using Java

>Compute amount of water that can trapped between the blocks using Java


Nisha Patel

Nisha Patel

Submit
0 Answers