当前位置:网站首页>[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,结束调用自身函数.
可能代码写的不是很好,希望兄弟们不要介意
边栏推荐
- gbase在轨道交通一般都采用哪种高可用架构?
- C#+WPF 单元测试项目类高级程序员必知必会
- 袋鼠云思枢:数驹 DTengine,助力企业构建高效的流批一体数据湖计算平台
- Leecode-SQL 1484. 按日期分组销售产品
- 智能合约是什么?
- 深度学习经典网络 -- Inception系列(稀疏结构)
- 浪潮—英伟达打造元宇宙新方案,虚拟人的故事将再破你的认知
- Dry goods!A highly structured and sparse linear transformation called Deformable Butterfly (DeBut)
- 【网络原理的概念】
- 在 Chrome 开发者工具里通过 network 选项模拟网站的离线访问模式
猜你喜欢

MySQL database combat (1)

训练双塔检索模型,可以不用query-doc样本了?明星机构联合发文

Polymorphism in detail (simple implementation to buy tickets system simulation, covering/weight definition, principle of polymorphism, virtual table)

Win10/11 删除文件资源管理器左侧栏目文件夹

How to use outside the PHP command in the container

go——并发编程

程序员架构修炼之道:如何设计出可持续演进的系统架构?

鸿蒙第三次

苏州大学:从PostgreSQL到TDengine

像用户体验设计师一样思考
随机推荐
分布式事务七种解决方案
Machine Learning Overview
HCIP第十七天笔记
How to retrieve IDC research reports?
后台图库上传功能
再谈“雷克萨斯”安全装置失效!安全手册疑点重重,网友:细思极恐
MATLAB programming and application 2.7 Structural data and unit data
MySQL数据库基本使用
LeetCode_多叉树_中等_429.N 叉树的层序遍历
MySQL数据库实战(1)
多态详细讲解(简单实现买票系统模拟,覆盖/重定义,多态原理,虚表)
This article understands the process from RS485 sensor to IoT gateway to cloud platform
消费者认可度较高 地理标志农产品为啥“香”
Regulation action for one hundred days during the summer, more than 700 traffic safety hidden dangers were thrown out
LyScript 实现对内存堆栈扫描
三大产品力赋能欧萌达OMODA5
【Star项目】小帽飞机大战(九)
面试一面
How to deal with this time of MySQL binlog??
【TypeScript】为什么要选择 TypeScript?