Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split 4 digit integer in Java

Tags:

java

int

I want to split a 4-digit integer in to 2. i.e convert 1234 into two variables; x=12 and y=34. Using Java.

like image 218
Tiffany Kim Schreuder Avatar asked Jan 16 '23 20:01

Tiffany Kim Schreuder


1 Answers

int four = 1234;  
int first = four / 100;   
int second = four % 100; 

the first one works because integers are always rounded down, stripping the last two digits when divided by 100.

the second one is called modulo, dividing by 100 and then taking the rest. this strips all digits exept the first two.

Lets say you have a variable number of digits:

int a = 1234, int x = 2, int y = 2; 
int lengthoffirstblock = x; 
int lengthofsecondblock = y;
int lengthofnumber = (a ==0) ? 1 : (int)Math.log10(a) + 1; 
//getting the digit-count from a without string-conversion   

How can I count the digits in an integer without a string cast?

int first = a / Math.pow(10 , (lengthofnumber - lengthoffirstblock));
int second = a % Math.pow(10 , lengthofsecondblock); 

and at the end something usefull if you have cases where the input could be negative:

Math.abs(a); 
like image 179
reggaemuffin Avatar answered Jan 24 '23 12:01

reggaemuffin