用的C++ class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
const int n = digits.size();
vector<int> result;
long int num=0;
for(int i = 0;i < n;i++){
num += digits[i]*pow(10,n-i-1);
}
num++;
while(num > 0){
int i = num % 10;
num /= 10;
result.push_back(i);
}
reverse(result.begin(),result.end());
return result;
}
};输入: [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]输出: [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,4,0,9]预期: [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]不一样,通过109个例子中的79个
1 回答
守候你守候我
TA贡献1802条经验 获得超10个赞
for循环里改成这个num += digits[i]*(long int)pow(10,n-i-1);pow默认返回int,丢失精度;
另外这题你这么做AC不了的应该,给的数据范围已经超long long了,你应该模拟数学加法运算去做。这是我AC的代码
class Solution {
public:
vector plusOne(vector& digits) {
int n = digits.size();
if(0 == n) return vector{0};
vector ans;
int c = 1; //进位
for(int i = n - 1; i >= 0; --i)
{
ans.push_back(digits[i] + c);
c = ans[ans.size() - 1] / 10;
ans[ans.size() - 1] %= 10;
}
if(1 == c)
{//在首位加1
ans.push_back(1);
}
reverse(ans.begin(), ans.end());
return ans;
}
};
- 1 回答
- 0 关注
- 631 浏览
添加回答
举报
0/150
提交
取消