简体   繁体   English

在Java中拆分4位整数

[英]Split 4 digit integer in Java

I want to split a 4-digit integer in to 2. ie convert 1234 into two variables; 我想将4位整数分成2,即将1234转换为两个变量; x=12 and y=34 . x=12y=34 Using Java. 使用Java。

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. 第一个是有效的,因为整数总是向下舍入,当除以100时剥去最后两位数。

the second one is called modulo, dividing by 100 and then taking the rest. 第二个被称为模数,除以100然后取其余部分。 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); 
int a = 1234;
int x = a / 100;
int y = a % 100;
int i = 1234;
int x = 1234 / 100;
int y = i - x * 100;

You can treat it as a string and split it using substring() , or as an integer: 您可以将其视为字符串并使用substring()或整数将其拆分:

int s = 1234;
int x = s / 100;
int y = s % 100;

If it's originally an int, I'd keep it as an int and do the above. 如果它最初是一个int,我会将它保存为int并执行上述操作。

Note that you need to consider what happens if your input is not four digit. 请注意,如果输入不是四位数,则需要考虑会发生什么。 eg 123. 例如123。

In case you want to split the same no: 如果你想拆分相同的no:

int number=1234;
int n,x,y;         //(here n=1000,x=y=1)   
int f1=(1234/n)*x; //(i.e. will be your first splitter part where you define x)
int f2=(1234%n)*y; //(secend splitter part where you will define y)

If you want to split the number in (12*x,34*y){where x=multiple/factor of 12 & y=multiple/factor of 34),then 如果你想将数字分成(12 * x,34 * y){其中x =倍数/因子12&y =倍数/因子34),那么

1234=f(x(12),y(34))=f(36,68) 1234 = F(X(12),Y(34))= F(36,68)

int number=1234;
int n;        //(here n=1000)  
int x=3;
int y=2; 
int f1=(1234/n)*x; //(i.e. will be your first splitter part where you define x)
int f2=(1234%n)*y; //(secend splitter part where you will define y)
int i = 1234;
int x = i / 100;
int y = i % 100;
    int num=1234;
    String text=""+num;
    String t1=text.substring(0, 2);
    String t2=text.substring(2, 4);
    int num1=Integer.valueOf(t1);
    int num2=Integer.valueOf(t2);
    System.out.println(num1+" "+num2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM