hulu面试(大整数加法)

来源:互联网 发布:历年网络炒作事件 编辑:程序博客网 时间:2024/05/21 21:36

周五参加了Hulu的笔试,70分钟的时间题量很大,自己准备得还是非常不充分,前面十道选择题就花去了40分钟时间,后面5道填空题只好蒙了。就这样时间还是很不够,考的题目都是比较基础的算法、数据结构,再加简单的推理。还是自身的原因。后面的算法题也很基础,大整数加法(可以比较下大整数乘法)。之前做过,不过由于时间原因,这次该注意的地方都没注意到。很是遗憾,这里是回来之后写的代码。提醒自己好好复习,不要浪费时间。


[cpp] view plaincopy


  • #include <iostream>  
  • using namespace std;  
  • int main()  
  • {  
  •         //string s1="3213124324131254356342652624624";  
  •         string s2="4";  
  •         string s1="9999999999999999999999999999999999999999999999";  
  •         if(s1.length() > s2.length())  
  •         {  
  •                 string tmp = s1;  
  •                 s1 = s2;  
  •                 s2 = tmp;  
  •         }  
  •         string result(s2.length(), '0');  
  •         int advance = 0;  
  •         int i, j;  
  •         for(i = s2.length() - 1, j = s1.length() - 1; j >= 0; --i, --j)  
  •         {  
  •                 result =((s1[j] - '0') + (s2 - '0') + advance) % 10 + '0';  
  •                 advance = ((s1[j] - '0') + (s2 - '0') + advance) / 10;  
  •         }  
  •         while(advance && i != -1)//trick 考虑到两者位数相等的情况,必须判断i是否为-1.  
  •         {  
  •                 result = ((s2 - '0') + advance) % 10 + '0';  
  •                 advance = ((s2 - '0') + advance) / 10;  
  •                 --i;  
  •         }  
  •         if(i != -1)  
  •         {  
  •                 while(i != -1)  
  •                 {  
  •                         result = s2;  
  •                         --i;  
  •                 }  
  •         }  
  •         else  
  •         {  
  •                 result.insert(result.begin(),advance + '0');  
  •         }  
  •         cout<<result<<endl;  
  •         return 0;  
  • }  
0 0