首页 > 代码库 > 每日算法之四十八:Plus One (数组表示的十进制加一进位)以及求Sqrt(x)
每日算法之四十八:Plus One (数组表示的十进制加一进位)以及求Sqrt(x)
给定数组表示的十进制数,加一操作。结果依然用十进制的数组表示。这里主要注意最高位(digit[0])依然有进位,即溢出的情况。
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
<span style="font-size:18px;">class Solution { public: vector<int> plusOne(vector<int> &digits) { int len = digits.size(); if(len == 0) return digits; int carry = 1;int temp = 0; for(int i = len-1; i>=0; i--) { temp = (digits[i] + carry)/10; digits[i] = (digits[i] + carry)%10; carry = temp; } if(carry > 0) { vector<int> ret(len+1, 0); ret[0] = 1; return ret; } else return digits; } };</span>
Sqrt(X):
class Solution { public: int sqrt(int x) { double diff = 0.01; // 误差 int low = 0; int high = x; while(low <= high){ // 注意越界!所以用double来存 double mid = low + (high-low)/2; if(abs(mid*mid-x) <= diff){ return (int)mid; }else if(x > mid*mid+diff){ low = (int)mid+1; }else if(x < mid*mid-diff){ high = (int)mid-1; } } // 当找不到时候,这是low,high指针已经交叉,取较小的,即high return high; } };
每日算法之四十八:Plus One (数组表示的十进制加一进位)以及求Sqrt(x)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。