How to split a number stored in a string and check if it is divisible by 495?

Asked

Viewed 267 times

1

For example a number that doesn’t fit in one int and I store in a String.

How do I see if it is divisible by 495?

2 answers

3

Why don’t you use class BigInteger to deal with these numbers?

You can use the function BigInteger#mod:

public static boolean divisivel(BigInteger numero, String divisor) {
    return numero.mod(new BigInteger(divisor)).equals(BigInteger.ZERO);
}

The above function should receive a BigInteger and a string with the divisor number, see an example:

public static void main (String[] args) throws java.lang.Exception
{
    System.out.println(divisivel(new BigInteger("495"), "495")); // true
    System.out.println(divisivel(new BigInteger("496"), "495")); // false
}

Complete code:

import java.io.*;
import java.math.BigInteger;

class Ideone
{
    public static boolean divisivel(BigInteger numero, String divisor) {
        return numero.mod(new BigInteger(divisor)).equals(BigInteger.ZERO);
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(divisivel(new BigInteger("495"), "495")); // true
        System.out.println(divisivel(new BigInteger("496"), "495")); // false
    }
}

See DEMO

  • I’m still a beginner.?

  • @Evandro I don’t think so, and use BigInteger is not difficult, what is the difficulty? Welcome, see the [tour] to understand how the site works!

0

To turn string into int or long you can do so...

Scanner s = new Scanner(System.in);
String str = s.nextLine();
try {
   int inteiro = Integer.parseInt(str);
   long longo = Long.parseDouble(str);
} catch (NumberFormatException e) {
   System.out.println("Numero com formato errado!");
}

Here your integer or long variable will have the value of your string, now just know if her division by 495 has zero rest.

if(i % 495 ==0){
System.out.println("É divisível");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.