user3566608
user3566608

Reputation: 353

How to add digits to a long value

So I have this variable long hashvalue and I want to add digits to it if something is true.

I have this array int arr[3][3] with the numbers -1, 1, 0, 0, -1, 1, 0, 0, -1 in it

I need something like this:

if(array[i][j] == -1){
    //add digit 2 to hashvalue
} else if(array[i][j] == 1){
    //add digit 1 to hashvalue
} else if(array[i][j] == 0){
    //add digit 0 to hashvalue
} 

hashvalue = 210021002

Upvotes: 2

Views: 818

Answers (2)

João Neves
João Neves

Reputation: 21

you can just multiply hashvalue by 10 and then add the wanted digit. Like:

if(array[i][j] == -1){
    hashValue = hashValue * 10 + 2;
} else if(array[i][j] == 1){
    hashValue = hashValue * 10 + 1;
} else if(array[i][j] == 0){
    hashValue = hashValue * 10 + 0;
} 

Imagine your hashValue starts with 3, if you multiply it by 10 it becomes 30, if you add the digit, let's say 2, it becomes 32. The digit has been added. I hope I helped!

Upvotes: 1

Para Black
Para Black

Reputation: 56

You can simply make a string for the hashvalue and adding the digits to the string via the + (or +=) operator. To receive a long object from the string, you can use the Long.parseLong() function.

String hashvalue = "";

// Add your digits to the String here
hashvalue += "1";

// Convert the String to a long
long finalHashvalue = Long.parseLong(hashvalue);

Upvotes: 3

Related Questions