hash表实现单位转换
in Algorithm Pageviews
某个公司因为业务扩展,需要到另一个星球做太空项目,由于运转周期与地球不同,不同单位的时长与地球有很大的差异,给定如下星球时长的单位以及换算规则如下:
1 year = 22month, 1month = 31 day, 1day = 24hour, 1hour = 60minute, 1minute = 60second;
根据输入,将其尽可能往较大单位转换;如果转换后为0,则跳过单位不再输出;
用例:
输入: ”489607 minute“
输出:”10month 30 day 7 minute”
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string UintTransForm(const string &str)
{
string number;
string time;
stringstream ss(str);
ss >> number >> time;
unordered_map<string, int> m_hashMap;
m_hashMap[time] = atoi(number.c_str());
vector<string> timeVec = {"second", "minute", "hour", "day", "month", "year"};
unordeded_map<string, int> standUnit =
{{"year", 0}, {"month", 22}, {"day", 31}, {"hour", 24}, {"minute", 60}, {"second", 60}};
unordeded_map<string, int> timeIdx =
{{"second", 0}, {"minute", 1}, {"hour", 2}, {"day", 3}, {"month", 4}, {"year", 5}};
while (m_hashMap[time] >= standUint[time] && (time != "year")) {
for (auto i = timeIdx[time]; i < timeVec.size() - 1; i++) {
if (time == timeVec[i]) {
m_hashMap[timeVec[i + 1]] = m_hashMap[time] / standUnit[time];
m_hashMap[time] = m_hashMap[time] % standUint[time];
time = timeVec[i + 1];
break;
}
}
}
string res;
for (const auto &[s, num] : m_hashMap) {
if (num != 0) {
res += to_string(num) + " " + str + " ";
}
}
res.resize(res.size() - 1);
return res;
}
};