当前位置:网站首页>[Output each bit of an integer, from high to low.With and without recursion]
[Output each bit of an integer, from high to low.With and without recursion]
2022-08-03 10:53:00 【DJL_new_life】
The future is scary but you can’t just run to the past cause it’s familiar.
未来会让人心生畏惧,但是我们却不能因为习惯了过去,就逃去过去.
题目:输出一个整数的的每一位,由高到低输出
这道题正常的思路是使用递归的方法去写,但是我在这里没有使用递归的方法去写.
思路是:假设判断出这个整数是一个n位的数字,再使用这个整数去除10^(n-1),就可以去掉除了最高位的数字,得到最高位,再对于这个整数取模10^(n-1),得到除了最高位以外的数字,重复进行以上操作
以下是完整代码:
import java.util.Scanner;
/** * 输出一个整数的每一位,如:123的每一位是1 , 2 , 3 * 从高位到低位输出 */
public class OutHignNums {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入整数:");
int a = scanner.nextInt();
int ret = a;
int i = 1;
//算出这个数有几位
while(ret/10 != 0){
ret = ret/10;
i++;
}
//只有一位数时,直接输出,无需进行下面的代码
if(i == 1){
System.out.println(a);
return;
}
for (int j = i-1; j >= 0; j--) {
double tens = Math.pow(10,j);
int num = (int)(a/tens); //得到最高位的数,此时a没有发生改变
//tens是double类型,需要强制类型转换为int,消除小数.
//否则得到的数字是小数,小数点后跟着低位的数
//每次输出整数的最高位
System.out.print(num + " ");
a = (int)(a % tens); //得到去掉最高位的数,继续下次循环
}
}
}
使用递归来解决输出一个整数的的每一位,由高到低输出.
public class Test2 {
public static void main(String[] args) {
prin(3239);
}
public static void prin(int a){
if(a > 9){
prin(a/10);
}
System.out.println(a%10);
}
}
递归的思路:
终止的条件是当 a<= 9时,输出a%10,程序结束.
if(a > 9){
prin(a/10);
}
这段代码的意思是:
当a > 9时,不断的调用自身函数,传入丢掉个位的数.直到a<= 9,结束调用自身函数.
可能代码写的不是很好,希望兄弟们不要介意
边栏推荐
- 如何改变sys_guid() 返回值类型
- How to use outside the PHP command in the container
- MapReduce中ETL数据清洗案例
- MATLAB programming and application 2.7 Structural data and unit data
- 巴比特 | 元宇宙每日必读:玩家离场,平台关停,数字藏品市场正逐渐降温,行业的未来究竟在哪里?...
- MySQL数据库实战(1)
- numpy
- 成对连接点云分割
- VL53L0X V2 laser ranging sensor collects distance data serial output
- 鸿蒙第四次
猜你喜欢

如何改变sys_guid() 返回值类型

巴比特 | 元宇宙每日必读:玩家离场,平台关停,数字藏品市场正逐渐降温,行业的未来究竟在哪里?...

Cross-chain bridge protocol Nomad suffers hacker attack, losing more than $150 million

消费者认可度较高 地理标志农产品为啥“香”

创建C UDR时,指定的HANDLESNULLS的作用是什么?

MySQL database combat (1)

三大产品力赋能欧萌达OMODA5

MySQL数据库实战(1)

Basic using MySQL database

type="module" you know, but type="importmap" you know
随机推荐
Matplotlib
numpy
Enter the SQL Client to create the table, in another node into the SQL Client queries
多态详细讲解(简单实现买票系统模拟,覆盖/重定义,多态原理,虚表)
DOM对象能干什么?
ScrollView嵌套RecyclerView滚动冲突
How to make self-introduction
LyScript 实现对内存堆栈扫描
全新的Uber App设计
完全背包问题的思路解析
CADEditorX ActiveX 14.1.X
RecyclerView的item高度自适应
error C2872: “flann”: 不明确的符号 解决方法
MATLAB Programming and Applications 2.6 Strings
mysql数据库定时备份占用大量线程,导致全局锁表,有啥好的解决方法么
科普大佬说 | 黑客帝国与6G有什么关系?
成对连接点云分割
509. 斐波那契数
ERC20通证标准是什么?
oracle计算同、环比