Given a non-negative integer rePResented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
還是先翻譯題目:
給定一個用非空數組表示的非負整數,對該整數加一,輸出新的用數組表示的整數;
這道題倒是不難,但是一直沒有通過是因為沒有掌握vector的用法,將vector當作是一個數組名然后直接
vector[size+1]=0;
是在這里出現了錯誤,一直都是在用例[9]那里無法通過;
還有一個沒搞清的問題是之前寫的另外一份出現了超時,對于超時還需要研究;
以下為解題思路:
由于數組第一位表示的是整數的高位,以此類推,所以先從數組的最后一位開始判斷,
如果是9,那么就加一,變為0,對其賦值為0,然后接著判斷其前面一位,如果不是9,則該位加一,
然后退出循環;
然后判斷是否出現全9的情況,如果出現全9,那么第一位必然是0,判斷第一位是否為0,若是,則將其賦值為
1,然后在末位加一個0;
以下為代碼示例:
class Solution {public: vector<int> plusOne(vector<int>& digits) { int i,j,temp; bool k; j=digits.size(); j--; for(int i=j;i>=0;i--){ if(digits[i]==9){ digits[i]=0; continue; } else{ temp=digits[i]; temp++; digits[i]=temp; break; } } if(digits[0]==0){ digits[0]=1; //temp=j; //temp++; digits.push_back(0); } return digits; }};class Solution {public:vector<int> plusOne(vector<int>& digits) {int i,j,temp;bool k;j=digits.size();j--;for(int i=j;i>=0;i--){if(digits[i]==9){digits[i]=0;continue;}else{temp=digits[i];temp++;digits[i]=temp;break;}}if(digits[0]==0){digits[0]=1;//temp=j;//temp++;digits.push_back(0);}return digits;}};
新聞熱點
疑難解答