Reputation: 47
How could I show only specific digit of an output? How could I delete 0's from a bigInteger?
My Example:
Having a task to show number's factorial's last number that isn't 0.
Example:
1! = 1
2! = 2
3! = 6
4! = 4
5! = 2
6! = 2
Right now it just shows factorial.
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
// Returns Factorial of N
static BigInteger factorial(int N){
// Initialize result
BigInteger f = new BigInteger("1"); // Or BigInteger.ONE
// Multiply f with 2, 3, ...N
for (int i = 2; i <= N; i++)
f = f.multiply(BigInteger.valueOf(i));
return f;
}
// Driver method
public static void main(String args[]) throws Exception
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println(factorial(n));
}
}
Example vol2 --> Here I need a solution to remove 0's from biginteger:
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
// Returns Factorial of N
static BigInteger factorial(int N){
// Initialize result
BigInteger f = new BigInteger("1"); // Or BigInteger.ONE
// Multiply f with 2, 3, ...N
for (int i = 2; i <= N; i++)
f = f.multiply(BigInteger.valueOf(i));
return f;
}
// Driver method
public static void main(String args[]) throws Exception
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
BigInteger a = (factorial(n));
BigInteger b, c;
c = new BigInteger("10");
b = a.mod(c);
System.out.println(b);
System.out.println(a);
}
}
Is there an easy way to remove all 0's from a number? That would be the easiest way to fix my problem
Upvotes: 2
Views: 172
Reputation: 22343
You could just convert your number into a string and remove the zeros. Then you put it back into BigInteger
:
public static BigInteger removeZeroes(int i) {
return new BigInteger(String.valueOf(i).replace("0", ""));
}
Upvotes: 5