簡體   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