Monday, December 15, 2014

Google onsite一题

Divide number and return result in form of a string. e.g 100/3 result should
be 33.(3) Here 3 is in brackets because it gets repeated continuously and 5
/10 should be 0.5.


Answer:
想法大概是,每一个iteration保留被除数,商和余数。小数点以后把被除数放在
一个hashtable里
面,如果被除数出现过,就把上一次被除数到这一次被除数之间的商重复。


5/10 返回0.5。有的面经让返回0.5(0)。这里返回0.5(0)。
string get_decimal(int num, int den) {
    string ret = to_string(num / den);
    ret.push_back('.');
    num %= den;
    map<int,int> rems;
  
    while(num != 0 && !rems.count(num)) {
        rems[num] = (int)ret.size();
        num *= 10;
        ret.push_back(num / den + '0');
        num %= den;
    }
  
    if (num != 0) {
        ret.insert(ret.begin() + rems[num], '(');
        ret += ")";
    } else {
        ret += "(0)";
    }
    return ret;
}

No comments:

Post a Comment