繁体   English   中英

在Java中拆分4位整数

[英]Split 4 digit integer in Java

我想将4位整数分成2,即将1234转换为两个变量; x=12y=34 使用Java。

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

第一个是有效的,因为整数总是向下舍入,当除以100时剥去最后两位数。

第二个被称为模数,除以100然后取其余部分。 这剥夺了前两个数字的所有数字。

假设您有一个可变位数:

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   

如何在没有字符串强制转换的情况下计算整数中的数字?

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

如果您的输入可能是负面的,那么最后会有用的东西:

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;

您可以将其视为字符串并使用substring()或整数将其拆分:

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

如果它最初是一个int,我会将它保存为int并执行上述操作。

请注意,如果输入不是四位数,则需要考虑会发生什么。 例如123。

如果你想拆分相同的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)

如果你想将数字分成(12 * x,34 * y){其中x =倍数/因子12&y =倍数/因子34),那么

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