当前位置:网站首页>[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,结束调用自身函数.
可能代码写的不是很好,希望兄弟们不要介意
边栏推荐
- Skills required to be a good architect: How to draw a system architecture that everyone will love?What's the secret?Come and open this article to see it!...
- 深入解析分布式文件系统的一致性的实现
- LeetCode_二分搜索_简单_367.有效的完全平方数
- 【多线程的相关内容】
- Web Server 设置缓存响应字段的一些推荐方案
- MySQL数据库基本使用
- Guys, I have a problem: My source mysql has a table that has been writing to, I use mysql cdc connec
- Leecode-SQL 1484. 按日期分组销售产品
- 怎么在外头使用容器里php命令
- 程序员架构修炼之道:软件架构基本概念和思维
猜你喜欢

跨域问题的分析

「全球数字经济大会」登陆 N 世界,融云提供通信云服务支持

成为优秀架构师必备技能:怎样才能画出让所有人赞不绝口的系统架构图?秘诀是什么?快来打开这篇文章看看吧!...

CADEditorX ActiveX 14.1.X

像用户体验设计师一样思考

LeetCode_多叉树_中等_429.N 叉树的层序遍历

Analysis of the idea of the complete knapsack problem

被审稿人吐槽没有novelty!深度学习方向怎么找创新点?

type="module" you know, but type="importmap" you know

月薪没到35K的程序员必须要背的面试八股,我先啃为敬!
随机推荐
Leecode-SQL 1667. 修复表中的名字
谷歌实用插件分享
MySQL database combat (1)
面试一面
LyScript 实现对内存堆栈扫描
如何通过DBeaver 连接 TDengine?
历史拉链数据处理有人做过吗
4 g acquisition ModbusTCP turn JSON MQTT cloud platform
被审稿人吐槽没有novelty!深度学习方向怎么找创新点?
Matplotlib
DOM对象能干什么?
Regulation action for one hundred days during the summer, more than 700 traffic safety hidden dangers were thrown out
程序员架构修炼之道:如何设计出可持续演进的系统架构?
Advanced use of MySQL database
三大产品力赋能欧萌达OMODA5
LeetCode_多叉树_中等_429.N 叉树的层序遍历
MySQL数据库基本使用
ARIMA实现(亲测可用)
servlet生命周期详解--【结合源码】
成为优秀架构师必备技能:怎样才能画出让所有人赞不绝口的系统架构图?秘诀是什么?快来打开这篇文章看看吧!...