倒序输出输入整数(使用栈)

public static int[] reverse(String name){
		In in=new In(name);
		Stack<Integer> input=new Stack<Integer>();
		while(!in.isEmpty()) {
			input.push(in.readInt());
		}
		int N=input.size();
		int[] a=new int[N];
		for(int i=0;i<N;i++) {
			a[i]=input.pop();
		}
		return a;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用实现10进制整数转换为2进制并倒序输出的程序: ```c #include <stdio.h> #include <stdlib.h> #define STACK_INIT_SIZE 100 #define STACK_INCREMENT 10 typedef struct { int *base; int *top; int stackSize; } Stack; int InitStack(Stack *S) { S->base = (int *)malloc(STACK_INIT_SIZE * sizeof(int)); if (!S->base) { exit(0); } S->top = S->base; S->stackSize = STACK_INIT_SIZE; return 1; } int Push(Stack *S, int e) { if (S->top - S->base >= S->stackSize) { S->base = (int *)realloc(S->base, (S->stackSize + STACK_INCREMENT) * sizeof(int)); if (!S->base) { exit(0); } S->top = S->base + S->stackSize; S->stackSize += STACK_INCREMENT; } *(S->top) = e; S->top++; return 1; } int Pop(Stack *S, int *e) { if (S->top == S->base) { return 0; } S->top--; *e = *(S->top); return 1; } int StackEmpty(Stack *S) { if (S->top == S->base) { return 1; } return 0; } int main() { int n, r; Stack S; InitStack(&S); printf("请输入一个十进制整数:"); scanf("%d", &n); while (n) { r = n % 2; Push(&S, r); n /= 2; } printf("转换为二进制后的结果:"); while (!StackEmpty(&S)) { Pop(&S, &r); printf("%d", r); } printf("\n"); return 0; } ``` 程序运行时,会提示用户输入一个十进制整数n,然后采用除2取余法将其转换为二进制,并倒序输出结果。 接下来,我们来测试一下程序的正确性。输入一个十进制整数15,程序输出的结果为: ``` 请输入一个十进制整数:15 转换为二进制后的结果:1111 ``` 结果符合预期,说明程序实现正确。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值