当前位置:网站首页>[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,结束调用自身函数.
可能代码写的不是很好,希望兄弟们不要介意
边栏推荐
- Advanced use of MySQL database
- 月薪没到35K的程序员必须要背的面试八股,我先啃为敬!
- 如何将Oracle/MySQL中的数据迁移到GBase 8c中?
- 聊天app开发——防炸麦以及节省成本的内容鉴定方法
- 面试一面
- 3D激光SLAM:LeGO-LOAM---两步优化的帧间里程计及代码分析
- Polymorphism in detail (simple implementation to buy tickets system simulation, covering/weight definition, principle of polymorphism, virtual table)
- Matplotlib
- VL53L0X V2 laser ranging sensor collects distance data serial output
- LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之二
猜你喜欢

鸿蒙第四次

【二分查找详解外加递归写法】附有全部代码

Who is more popular for hybrid products, depending on technology or market?

Basic using MySQL database

CADEditorX ActiveX 14.1.X

科普大佬说 | 黑客帝国与6G有什么关系?

Depth study of 100 cases - convolution neural network (CNN) to realize the clothing image classification

numpy

Matplotlib

Interview Blitz 71: What's the difference between GET and POST?
随机推荐
白帽黑客与留守儿童破壁对“画”!ISC、中国光华科技基金会、光明网携手启动数字安全元宇宙公益展
Basic using MySQL database
[Star Project] Little Hat Plane Battle (9)
Pixel mobile phone system
numpy
RecyclerView的item高度自适应
分布式事务七种解决方案
【文件IO的简单实现】
MySQL数据库高级使用
Boolean 与numeric 无法互转
关于OPENSSL的问题
跨域问题的分析
error C2872: “flann”: 不明确的符号 解决方法
Enter the SQL Client to create the table, in another node into the SQL Client queries
一文带你弄懂 CDN 技术的原理
鸿蒙第三次
QT with OpenGL(Shadow Mapping)(面光源篇)
How to deal with this time of MySQL binlog??
像用户体验设计师一样思考
Cross-chain bridge protocol Nomad suffers hacker attack, losing more than $150 million