从Java中的数字中删除数字 [英] Remove digits from a number in Java

查看:217
本文介绍了从Java中的数字中删除数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何删除整数的第一个数字?

How do I remove the first digit of an integer?

我的输入是一个整数(例如i = 123456789)。

My input is an integer (for example i = 123456789).

然后我要删除第一个数字,以便我等于23456789.

I then want to remove the first digit, so that i equals 23456789.

推荐答案

这是一种方法:


  • 将其转换为 String

  • 不带第一个数字的子字符串

  • 将其转换为 int

  • Convert it to String
  • Take the substring without the first "digit"
  • Convert it to int

代码:

public static void main(String[] args)
{
    int x = 123456789;

    String x_str = Integer.toString(x);

    int new_x = Integer.parseInt(x_str.substring(1));

    System.out.println(new_x);
}

输出:

23456789






注意:这可以在一行中完成

int x = 123456789;
int new_x = Integer.parseInt(Integer.toString(x).substring(1));

修改:

要处理否定的情况,请检查数字是正数还是整数:

To handle negative-case, check if number is positive or integer:

int new_x = Integer.parseInt(x > 0 ? 
    Integer.toString(x).substring(1) : Integer.toString(x).substring(2));

这篇关于从Java中的数字中删除数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆