zoukankan      html  css  js  c++  java
  • hdoj1002解题报告(大数入门)

    引言 : int最大能表示的数约在10^9,最大的long long也只能存储约在10^19范围内的数。那怎么进行大数的运算呢,拿起草稿纸,做一个加法运算,看看会有哪些步骤。

    题解 :

    用字符数组来存储大数,每一位当做一个字符,可以开多大的数组,就能计算多少位的数。

    举个栗子,计算99999999999+1.  直接用int,答案显然是错的。用两个字符数组

    s1 :

     9 9 9 9 9 9 9 9 9 9 9

    s2 :

     1

    再用字符数组s来存储两数之和,显然s最长为s1的长度加1。从最低位依次模拟加法,注意进位,注意字符0与数字0的区别,注意数组从0开始。

    s:

    1 0 0 0 0 0 0 0 0 0

    #include<stdio.h>
    #include<string.h>
    
    void  Bignum_add(char * s1,char * s2,char *s)
    {    int i,j,a,l1,l2,L,t;
        
        l1=strlen(s1);
        l2=strlen(s2);
        s[0]='0';
        a=0;
        if(l1>l2) L=l1;  
        else L=l2; 
    	s[L+1]='';     
        for(i=L;l1>0&&l2>0;i--)
        {
            a=(s1[--l1]-'0')+(s2[--l2]-'0')+a/10;
            s[i]=a%10+'0';
        }
        while(l1){
            a=(s1[--l1]-'0')+a/10;
            s[i--]=a%10+'0';
                }
        while(l2){
            a=(s2[--l2]-'0')+a/10;
            s[i--]=a%10+'0';
                }
        s[i]=a/10+'0';
        
        t=0;
        while(s[t]=='0'&&t<L) t++;  
        
        strcpy(s,s+t);    //比如,将000001化成1
    }
    
    int main()
    {	int T,d=1;
    	char s[1000],s1[1000],s2[1000];
    	scanf("%d",&T);
    	while(T--)
    	{	scanf("%s%s",s1,s2);
    		Bignum_add(s1,s2,s);
    		printf("Case %d:
    ",d++);	
    		printf("%s + %s = %s
    ",s1,s2,s);
    		if(T!=0) printf("
    ");
    		
    	} 
     
     return 0;
    }
    

      

  • 相关阅读:
    BZOJ5212 ZJOI2018历史(LCT)
    BZOJ5127 数据校验
    253. Meeting Rooms II
    311. Sparse Matrix Multiplication
    254. Factor Combinations
    250. Count Univalue Subtrees
    259. 3Sum Smaller
    156. Binary Tree Upside Down
    360. Sort Transformed Array
    348. Design Tic-Tac-Toe
  • 原文地址:https://www.cnblogs.com/lnu161403214/p/7834144.html
Copyright © 2011-2022 走看看