[LeetCode]Plus One
Given a number represented as an array of digits, plus one to the number.hint : 类似于字符串模拟加减法的思路:
class Solution { public: vector<int> plusOne(vector<int> &digits) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<int> res; if(digits.size() == 0) return res; int carry = 1; int sum ; for(int i = digits.size() - 1; i >=0; i--) { sum = carry + digits[i]; carry = sum / 10; sum %= 10; res.push_back(sum); } if(carry == 1) res.push_back(1); reverse(res.begin(),res.end()); return res; } };
java什么的:
public class Solution { public int[] plusOne(int[] digits) { // Note: The Solution object is instantiated only once and is reused by each test case. int len = digits.length; for(int i = len-1; i >= 0; i--) { if(digits[i] != 9) { digits[i]++; return digits; } else digits[i] = 0; } int[] res = new int[len+1]; res[0] = 1; return res; } }
补充:软件开发 , C++ ,