What is the modulo operator for longs in Java? - java

How do I find the modulo (%) of two long values in Java? My code says 'Integer number too large' followed by the number I'm trying to mod. I tried casting it to a long but it didn't work. Do I have to convert it to a BigInteger and use the remainder method? Thanks.

The % operator does work for longs. It sounds like you may have forgotten to stick L at the end of a numeric literal, as in 123456789L. Can we see your code?

You can only have an integer up to 2 147 483 647. If you want to go bigger than that, say 3 billion, you must specify it to be a long
class Descartes {
public static void main(String[] args) {
long orig = Long.MAX_VALUE;
long mod = orig % 3000000000; // ERROR 3000000000 too big
long mod = orig % 3000000000L; // no error, specified as a long with the L
}
}
Keep in mind that you can use capital OR lowercase L, but it's advisable to use capital, since the lowercase looks remarkably similar to the number 1.

You can also try working with the BigInteger class which has a remainder() method that works similarly to %.

Related

How to convert int value 09 to char array as {'0','9'}?

I am working on the problem to find the next greatest number with the same set of digits.
For this I take a integer value input from the user and I want to convert to char array or int array so that I can access individual digits.
But when I take
int value=09 as the input and convert to char array it gives only 9 as it considers it to be octal value. How can I overcome this ?
it is not possible in java to take the int values with leading zeros.
so for the value with leading zeros take it in string format.
but we can insert zeros
int n=7;
String str=String.format("%04d", n); //4 denotes the size of the string
System.out.println(str); // o/p->0007
It is not possible convert a 09 int value to a String of 9 since the value 09 can not be stored in an int.
int is not capable of storing trailing zeros.
Take this sample.
int foo = Integer.valueOf("09");
System.out.println(foo);
Output
9
So to solve your problem you should get a String from the user, validate it and parse it to an Integer[].
Solution
public Integer[] parseToInteger(String number) {
return Arrays.asList(number.toCharArray())
.stream()
.map(c -> Integer.valueOf(c.toString()))
.toArray(size -> new Integer[size]);
}
Now you have an Array of Integer.
Since leading 0's are dropped from integers there is no reason to support assigning such a value to an int.
If I want to convert 9 to '9' I usually just add '0' to it.
You can also do the following:
char c = Character.forDigit(9,10);
If you have a string of characters, you can do the following:
String str = "09";
List<Character> chrs =
str.chars().mapToObj(a -> Character.valueOf((char) a))
.collect(Collectors.toList());
System.out.println(chrs);
Prints
[0,9]
You are asking how to parse a number starting with a leading zero, but I get the feeling that you are actually on the worng track given the problem you are trying to resolve. So let's take one step backward, and lets make sure I understand your problem correctly.
You say that you have to find the "next greatest number with the same set of digits". So you are playing "Scrabble" with digits, trying to find the smalest number composed with the same digits that is strictly greater to the original number. For example, given the input "09", you would output "90", and for "123", you would output "132". Is that right? Let assume so.
Now, the real challenge here is how to determine the smalest number composed with thise digits that is stricly greater to the original number. Actually, there's a few possible strategies:
Enumerate all possible permutations of those digits, then filter out those that are not strictly greater to the original number, and then, among the remaining values, find the smallest value. That would be a very innefficient strategy, requiring both disproportionate memory and processing power. Please, don't consider this seriously (that is, unless you are actually coding for a Quantum Computer ;) ).
Set a variable to the initial number, then iteratively increment that variable by one until you eventually get a number that is composed of the same digits as the original values. That one might look simple to implement, but it actually hides some complexities (i.e. determining that two numbers are composed from the same digits is not trivial, special handling would be required to avoid endless loop if the initial number is actually the greatest value that can be formed with those digits). Anyway, this strategy would also be rather innefficient, requiring considerable processing power.
Iterate over the digits themselves, and determine exactly which digits have to be swapped/reordered to get the next number. This is actually very simple to implement (I just wrote it in less that 5 minutes), but require some thinking first. The algorithm is O(n log n), where n is the length of the number (in digits). Take a sheet of paper, write example numbers in columns, and try to understand the logic behind it. This is definitely the way to go.
All three strategies have one thing in common: they all require that you work (at some point at least) with digits rather than with the number itself. In the last strategy, you actually never need the actual value itself. You are simply playing Scrabble, with digits rather than letters.
So assuming you indeed want to implement strategy 3, here is what your main method might looks like (I wont expand more on this one, comments should be far enough):
public static void main(String[] args) {
// Read input number and parse it into an array of digit
String inputText = readLineFromUser();
int[] inputDigits = parseToDigits(inputText);
// Determine the next greater number
int[] outputDigits = findNextGreaterNumber(inputDigits);
// Output the resulting value
String outputText = joinDigits(outputDigits);
println(outputText);
}
So here's the point of all this discussion: the parseToDigits method takes a String and return an array of digits (I used int here to keep things simpler, but byte would actually have been enough). So basically, you want to take the characters of the input string, and convert that array to an array of integer, with each position in the output containing the value of the corresponding digit in the input. This can be written in various ways in Java, but I think the most simple would be with a simple for loop:
public static int[] parseToDigits(String input) {
char[] chars = input.toCharArray();
int[] digits = new int[chars.length];
for (int i = 0 ; i < chars.length ; i++)
digits[i] = Character.forDigit(chars[i], 10);
return digits;
}
Note that Character.forDigit(digit, radix) returns the value of character digit in base radix; if digit is not valid for the given base, forDigit returns 0. For simplicity, I'm skipping proper validation checking here. One could consider calling Character.isDigit(digit, radix) first to determine if a digit is acceptable, throwing an exception if it is not.
As to the opposite opperation, joinDigits, it would looks like:
public static String joinDigits(int[] digits) {
char[] chars = new char[digits.length];
for (int i = 0 ; i < digits.length ; i++)
chars[i] = Character.digit(digits[i], 10);
return new String(chars);
}
Hope that helps.

when I compile this code I get error like Integer number too large. Though I declare it as long, I don't know why it is showing error?

why I am getting error integer too large. As I declare it as long.
Here is my code
Scanner sc = new Scanner(System.in);
long x=sc.nextLong();
if(x>=-9223372036854775807 && x<=9223372036854775806)
System.out.println("long");
Put an "L" at the end of your numbers:
if(x>=-9223372036854775807L && x<=9223372036854775806L) System.out.println("long");
Such that the compiler sees them as longs, not ints.
By default all constant numbers all int, so you need to put L at the end of your numbers: 9223372036854775806L
But, the better way is using Long.MAX_VALUE and Long.MIN_VALUE instead of hard coding those large numbers.
You are not getting this error because of your x variable you are getting it because of number literals -9223372036854775807 and 9223372036854775806.
Because by default number literals are treated as int and you need to append an extra L at end of them to tell compiler to treat them as long literal.
How ever you should use Long.MAX_VALUE and Long.MIN_VALUE constants for this comparison. If your max and min value varies from the Long.MIN_VALUE and Long.MAX_VALUE, it is a best practice to create constants for them and then use them e.g.
final static long MIN_VALUE = 100000L;
final static long MAX_VALUE = 10000000L;
if(x<MIN_VALUE && x>MAX_VALUE) System.out.println("This is an invalid value");

Negate int using XOR and addition

I have to write a method which converts an int value to the same negative int value. For example, if the user types in 5 the method should give back -5.
The whole story is:
The method has a transfer parameter which is either a positive or a negative int. Is it a positive int, we should change it to a negative int. If it is a negative int, do nothing.
It is also hard to check if the given int is positive or negative.
The regulations:
I'm only allowed to use the arithmetic operation + and all the boolean operations. But in this case I know that I have to use XOR.
It's not about writing the method and all the JAVA stuff. It's just the logic I struggle with.
How can I change a value to its negative value using only XOR and +?
ATTENTION:
The only operations allowed are:
!
^
&&
||
+
No *, no -, no ~
Edit:
The two solutions from CherryDT and MikeC are working well. Any ideas how to check if its a negative or a positive parameter with the same regulations? I thought this would be the easy part. Then realized it isn't.
(x ^ -1) + 1
Explanation: Basically, it's the same as ~x + 1. -1 has all bits set, and therefore inverts all bits when XORed with, just like NOT. And since, the other way round, inverting will always give you -x - 1, all you need to do is invert and add 1.
Here we go
public class Test {
public static void main(String []args){
int x = 245;
System.out.println(x);
x = (~x^x)*x;
System.out.println(x);
}
}

what should be the primitive type of an integer with size 9bytes or more than 9 bytes?

I am creating a bank account.which has a 'accnum' as variable.which has integer value with size of 12 bytes.
let say the bank account number is 180020131111.How do you initialize to a variable?
public class number{
public static void main(String[] args){
private long x=180020131111; // is not working..
System.out.println(x);
}
}
180020131111 is an integer literal, which cannot fit into an int type. You should append an L at the end to make it long literal.
private long x = 180020131111L;
Well, I would rather store account number as String. I don't think there is really any need for storing it as numeral, as you are just going to display it. I mean it would really look weird if you are going to do some arithmetic operations on account numbers.
By default Integral Literals are treated as 32 bit int and not 64 bit long in java..
Use this
private long x=180020131111L;
The character l ot L at the end makes integral literals long
The largest Java primitive integral type is long which is a 64 bit (8 byte) signed type. If you want to represent numbers larger that 263 - 1 == 9,223,372,036,854,775,807, you need to use BigInteger or BigDecimal.
The problem with this statement ...
private long x=180020131111;
... is that you are using the syntax for an int literal. A long literal requires a l or L suffix. (FWIW - this number does not require 9 bytes to represent ...)

Calculate number of decimal digits in BigInteger

I'm trying to use BigInteger values along side Math.Log10 method.
final BigInteger answerNo = fact;
final int digits = 1 + (int)Math.floor(Math.log10(answerNo));
Unfortunately the compiler says incompatible types.
If I change the ints to BigIntegers it still doesn't like it.
Instead of doing a log10 you can find the number of digits by simply doing:
int digits = answerNo.toString().length();
You can't assign an int to a BigInteger - you could write: final BigInteger answerNo = BigInteger.valueOf(fact);
Mat.log10 expects a double, not a BigInteger
If you don't mind a loss of precision, you could simply use doubles:
final int digits = 1 + (int)Math.floor(Math.log10(fact));
If you care about precision, you will need to calculate the log manually.
BigInteger.toString() can be inefficient in terms of memory if you only care for count of digits.
You can instead try converting BigInteger into a BigDecimal and use the BigDecimal.precision() to achieve the same. See this answer for details.

Categories