A1023 Have Fun with Numbers (20分

2020-02-14  本文已影响0人  km15

/*
题意:
1给一个数字,然后双倍,看仍是否有这些个数字组成
这个数字不超过20个数

解题:
1、用散列,散列到每个数,并且有一个num++,
2、然后大整数乘法
3、再判断每个数是否散列中的数,如果是,则减减,并且num--,最后判断num是否为0

learn && wrong:
1、
标准答案不是我的散列,
(1)是先比较两个数长度是否相同,
(2)相同则,先让a.d[i]在count散列数组++,另外一个--,
(3)最后遍历一次count,
如果数字不止20,那就这个复杂度好点,如果只有20,那就差不多
我遍历了两次,它是遍历一次+遍历count(count只有9个下标
*/

#include <iostream>
#include <cstring>
using namespace std;

//结构体 
struct bign{
    int d[21];
    int len;
    bign(){
        memset(d,0,sizeof(d));
        len = 0;
    } 
};

//转换函数
bign change(char str[]){
    bign c;
    c.len = strlen(str);
    for(int i = 0;i < c.len;++i){
        c.d[i] = str[c.len - i - 1] - '0';
    }
    return c;
}

//乘法
bign multiple(bign a){
    bign c;
    int carry = 0;
    for(int i = 0;i < a.len;++i){
        int temp = a.d[i] * 2 + carry;
        c.d[c.len++] = temp % 10;
        carry = temp / 10;
    }
    while(carry != 0){
        c.d[c.len++] = carry % 10;
        carry /= 10;
    }
    return c;
} 

void print(bign a){
    for(int i = a.len - 1;i >= 0;--i){
        cout<<a.d[i];
    }
}

int hashtable[10] = {0};    //hashtable 
int main(int argc, char** argv) {
    char str1[21];
    cin>>str1;
    int len1 = strlen(str1);
    
    int num = 0;
    for(int i = 0;i < len1;++i){    //统计出现的数符 
        ++hashtable[str1[i] - '0']; 
        ++num;
    }   
    
    bign a = change(str1);  //实现乘法 
    a = multiple(a);
    
    for(int i = 0;i < a.len;++i){   //遍历a.d[i],判断hashtable该位是否大于0,如果存在,那就减减,并且num也渐渐,遍历完判断是num是否为0 
        if(hashtable[a.d[i]] > 0){
            --hashtable[a.d[i]];
            num--;
        }else break;
    }
    
    if(num == 0){
        cout<<"Yes"<<endl;
        print(a);
    }else{
        cout<<"No"<<endl;
        print(a);
    }
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读