java string to bit_String to 32 bit Integer in Java, with default value than exception

I have a string of signed integer value that could range from "+2147483650" to "-9638527412". I need to parse them to a 32-bit integer, such that, when the string value is above the integer capacity (2^31) it should return the nearest possible integer value. Using "Integer.parseInt" is giving out of bound exception.

Example:

input: "+2147483650"

output: "+2147483647"

input: ""-963852741258"

output: "-2147483648"

I tried to use existing functions, but I'm stuck here.

try{

//num =Integer.valueOf(stringNumber);

num =Integer.parseInt(stringNumber);

}catch(Exception e){

num = -2147483648; // if stringNumber is negative

num = +2147483647 // if stringNumber is positive

}

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

Since your value range is limited to "+2147483650" to "-9638527412", you can parse to long and check for overflow.

public static int parse(String stringNumber) {

long value = Long.parseLong(stringNumber);

return (value < Integer.MIN_VALUE ? Integer.MIN_VALUE :

value > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) value);

}

Test

System.out.println(parse("+2147483650"));

System.out.println(parse("42"));

System.out.println(parse("-9638527412"));

Output

2147483647

42

-2147483648

# Answer 2

If there is no reason you can't use a larger datatype such as Long then you can just parse it as a Long. If the parse fails, it will throw a NumberFormatException.

try {

long tmp = Long.parseLong(stringNumber);

int result;

if (tmp < Integer.MIN_VALUE) {

result = Integer.MIN_VALUE;

} else if (tmp > Integer.MAX_VALUE) {

result = Integer.MAX_VALUE;

} else {

// safe cast to int (java 8)

result = Math.toIntExact(tmp);

}

// TODO do something with the result

} catch (NumberFormatException e) {

// could not parse

}

# Answer 3

Given the specified potential input range, this function will clamp the given string in the range [Integer.MIN_VALUE, Integer.MAX_VALUE]:

static int clampedStringValue(String s) {

long n = Long.parseLong(s);

if (n > Integer.MAX_VALUE) {

return Integer.MAX_VALUE;

} else if (n < Integer.MIN_VALUE) {

return Integer.MIN_VALUE;

} else {

return (int)n;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值