gpt4 book ai didi

java - 在 Java 中拆分 4 位整数

转载 作者:搜寻专家 更新时间:2023-11-01 01:36:27 24 4
gpt4 key购买 nike

我想将一个 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

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);

如果您遇到输入可能为负的情况,最后会有些有用的东西:

Math.abs(a); 

关于java - 在 Java 中拆分 4 位整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11900147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com