当前位置:网站首页>[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,结束调用自身函数.
可能代码写的不是很好,希望兄弟们不要介意
边栏推荐
- 关于OPENSSL的问题
- With strong network, China mobile to calculate excitation surging energy network construction
- MATLAB programming and application 2.7 Structural data and unit data
- 玉溪卷烟厂通过正确选择时序数据库 轻松应对超万亿行数据
- 【无标题】函数,对象,方法的区别
- The way of programmer architecture practice: how to design a sustainable evolution system architecture?
- Cross-chain bridge protocol Nomad suffers hacker attack, losing more than $150 million
- 像用户体验设计师一样思考
- Mysql OCP 73 questions
- Mysql OCP 74 questions
猜你喜欢
随机推荐
MySQL数据库实战(1)
用于发票处理的 DocuWare,摆脱纸张和数据输入的束缚,自动处理所有收到的发票
Why is the new earth blurred, in-depth analysis of white balls, viewing pictures, and downloading problems
程序员架构修炼之道:软件架构基本概念和思维
_GLIBCXX_USE_CXX11_ABI 宏的作用
如何检索IDC研究报告?
Depth study of 100 cases - convolution neural network (CNN) to realize the clothing image classification
STM32+OLED显示屏制作指针式电子钟
请问应该用什么关键字将内容主题设置为 dark 呢
Mysql OCP 75 questions
Classical Architecture and Memory Classification of Embedded Software Components
ARIMA实现(亲测可用)
Leecode-SQL 1527. 模糊查询匹配(模糊查询用法)
With strong network, China mobile to calculate excitation surging energy network construction
4 g acquisition ModbusTCP turn JSON MQTT cloud platform
孙宇晨式“溢价逻辑”:不局限眼前,为全人类的“星辰大海”大胆下注
Basic using MySQL database
【二分查找详解外加递归写法】附有全部代码
3分钟实现内网穿透(基于ngrok实现)
go——并发编程