当前位置:网站首页>[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,结束调用自身函数.
可能代码写的不是很好,希望兄弟们不要介意
边栏推荐
- MATLAB程序设计与应用 2.6 字符串
- 数字藏品和ICP
- ETL data cleaning case in MapReduce
- How to retrieve IDC research reports?
- Cross-chain bridge protocol Nomad suffers hacker attack, losing more than $150 million
- Interview Blitz 71: What's the difference between GET and POST?
- LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之二
- 嵌入式软件组件经典架构与存储器分类
- Question G: Word Analysis ← Questions for the second provincial competition of the 11th Blue Bridge Cup Competition
- build --repot
猜你喜欢
训练双塔检索模型,可以不用query-doc样本了?明星机构联合发文
程序员架构修炼之道:软件架构基本概念和思维
【二分查找详解外加递归写法】附有全部代码
嵌入式软件组件经典架构与存储器分类
STM32+OLED显示屏制作指针式电子钟
再谈“雷克萨斯”安全装置失效!安全手册疑点重重,网友:细思极恐
【冒泡排序以及奇数偶数排列】
Dry goods!A highly structured and sparse linear transformation called Deformable Butterfly (DeBut)
Analysis of the idea of the complete knapsack problem
干货!一种被称为Deformable Butterfly(DeBut)的高度结构化且稀疏的线性变换
随机推荐
【输出一个整数的的每一位,由高到低输出。使用递归和不使用递归】
程序员架构修炼之道:如何设计出可持续演进的系统架构?
面试一面
被审稿人吐槽没有novelty!深度学习方向怎么找创新点?
complete knapsack problem
如何检索IDC研究报告?
ETL data cleaning case in MapReduce
type="module" you know, but type="importmap" you know
消费者认可度较高 地理标志农产品为啥“香”
袋鼠云思枢:数驹 DTengine,助力企业构建高效的流批一体数据湖计算平台
redis基础知识总结——数据类型(字符串,列表,集合,哈希,集合)
ERC20通证标准是什么?
创建C UDR时,指定的HANDLESNULLS的作用是什么?
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之二
巴比特 | 元宇宙每日必读:玩家离场,平台关停,数字藏品市场正逐渐降温,行业的未来究竟在哪里?...
Mysql OCP 74 questions
玉溪卷烟厂通过正确选择时序数据库 轻松应对超万亿行数据
如何改变sys_guid() 返回值类型
怎么在外头使用容器里php命令
Why is the new earth blurred, in-depth analysis of white balls, viewing pictures, and downloading problems