本篇內容介紹了“C++怎么實現加一運算”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Example 3:
Input: digits = [0]
Output: [1]
Constraints:
1 <= digits.length <= 100
0 <= digits[i] <= 9
將一個數字的每個位上的數字分別存到一個一維向量中,最高位在最開頭,我們需要給這個數字加一,即在末尾數字加一,如果末尾數字是9,那么則會有進位問題,而如果前面位上的數字仍為9,則需要繼續向前進位。具體算法如下:首先判斷最后一位是否為9,若不是,直接加一返回,若是,則該位賦0,再繼續查前一位,同樣的方法,知道查完第一位。如果第一位原本為9,加一后會產生新的一位,那么最后要做的是,查運算完的第一位是否為0,如果是,則在最前頭加一個1。代碼如下:
C++ 解法一:
class Solution { public: vector<int> plusOne(vector<int> &digits) { int n = digits.size(); for (int i = n - 1; i >= 0; --i) { if (digits[i] == 9) digits[i] = 0; else { digits[i] += 1; return digits; } } if (digits.front() == 0) digits.insert(digits.begin(), 1); return digits; } };
Java 解法一:
public class Solution { public int[] plusOne(int[] digits) { int n = digits.length; for (int i = digits.length - 1; i >= 0; --i) { if (digits[i] < 9) { ++digits[i]; return digits; } digits[i] = 0; } int[] res = new int[n + 1]; res[0] = 1; return res; } }
我們也可以使用跟之前那道 Add Binary 類似的做法,將 carry 初始化為1,然后相當于 digits 加了一個0,處理方法跟之前那道題一樣,參見代碼如下:
C++ 解法二 :
class Solution { public: vector<int> plusOne(vector<int>& digits) { if (digits.empty()) return digits; int carry = 1, n = digits.size(); for (int i = n - 1; i >= 0; --i) { if (carry == 0) return digits; int sum = digits[i] + carry; digits[i] = sum % 10; carry = sum / 10; } if (carry == 1) digits.insert(digits.begin(), 1); return digits; } };
Java 解法二 :
public class Solution { public int[] plusOne(int[] digits) { if (digits.length == 0) return digits; int carry = 1, n = digits.length; for (int i = digits.length - 1; i >= 0; --i) { if (carry == 0) return digits; int sum = digits[i] + carry; digits[i] = sum % 10; carry = sum / 10; } int[] res = new int[n + 1]; res[0] = 1; return carry == 0 ? digits : res; } }
“C++怎么實現加一運算”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。