在Java中提取int的数字 [英] Extracting digits of int in Java

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

问题描述

所以,如果我有一个输入的整数:

So if I have an inputted integer:

int num_1 = 128

我如何能够解析数字并获得1,2和8,并将它们分配给不同的变量?

How would I be able to parse through the number and obtain a 1, 2 and 8, and assign them to different variables?

谢谢!

推荐答案

执行此操作的低效方法是将整数转换为a字符串并迭代字符串字符。

the inefficient way to do this would be to convert the integer to a string and iterate on the string characters.

更有效的方式是:

int n = 128;
while (n > 0) {
  int d = n / 10;
  int k = n - d * 10;
  n = d;
  System.out.println(k);
}

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

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