剑指Offer 题目1515:打印1到最大的N位数

http://ac.jobdu.com/problem.php?pid=1515


题目本身太low,还是趁这个机会练练大数运算比较好。下面提供两种写法,C++纯手写大数计算,和JAVA大数类,如果机考,还是JAVA大数类吧。


#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>


using namespace std;

const int SIZE = 100+1;
int n;

void printNum(int num[]){
	int flag=1;
	for(int i=SIZE-n;i<SIZE;i++){
        if(num[i] != 0){
            flag=0;
        }
		if(!flag){
			printf("%d", num[i]);
		}
	}
	putchar('\n');
}

bool incNum(int num[]){
	for(int j=SIZE-1;j>=SIZE-n;j--){
		if(j == SIZE-1){
			num[j]++;
		}
		if(num[j]>9){
			num[j]-=10;
			if(j - 1 >= SIZE-n ){
				num[j-1]++;
			}else{
				return 0;
			}
		}else{
			break;
		}
	}
	return 1;
}

int main(){

	int num[SIZE];
	int tp[SIZE];
	while(~scanf("%d",&n)){
		memset(num,0,sizeof(num));
		incNum(num);
		do{
			printNum(num);
			//system("pause");
		}while( incNum(num) );
	}
	return 0;
}

JAVA大数类

比较compareTo  

<   返回值为<0

>  返回值为>0

=  返回值为==0

可以参考:

http://blog.csdn.net/u011026968/article/details/39668263

http://ly5633.iteye.com/blog/1218724

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
			int n = sc.nextInt();
			StringBuffer sb = new StringBuffer();
			for(int i=0;i<n;i++){
				sb.append("9");
			}
			BigInteger limit = new BigInteger(sb.toString());
			BigInteger a = new BigInteger("1");
			BigInteger b = new BigInteger("1");
			while(a.compareTo(limit) < 0 || a.compareTo(limit) == 0){
				System.out.println(a.toString());
				a = a.add(b);
			}
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值