本文主要是介绍一个google的面试题 计算两个整数相除,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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.
这题难在怎么去判断循环和记录循环出现的位置
上代码:
#include "common.hpp"string caldec(int a, int b) {string s = "";int residue = a%b; unordered_map<int, int> residue_index; //记录出现过的残差的值和位置s += to_string(a/b);s += ".";int index = s.length();while(residue != 0 && residue_index.find(residue) == residue_index.end()) {residue_index[residue] = index++;s += to_string((residue*10)/b);residue = (residue*10)%b;}if(residue_index.find(residue) != residue_index.end()) {int i = residue_index[residue];s.insert(i, "(");s += ")";}if(s[s.length()-1] == '.') {s = s.substr(0, s.length() - 1);}return s;
}
//我最近比较喜欢用随机数进行测试
int main() {srand(time(NULL));for(int i=0; i<10; i++) {int a = rand()%101;int b = rand()%29;if(a > b && b != 0) {cout << "a = " << a << ", b = " << b << ", res = " << caldec(a, b) << endl;}}return 0;
}
这篇关于一个google的面试题 计算两个整数相除的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!