66. Plus One
My SubmissionsTotal Accepted: 77253 Total Submissions: 242942 Difficulty: EasyGiven 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.
Subscribe to see which companies asked this question
Hide Tags Array Math Show Similar Problems//首先理清思路:題目說用一個數組來代表一個非負的整數,數組中存儲著該數的每一個位 //顯然數組的末尾是數的最低位,開始是最高位 //如果低位小於9,顯然直接+1就可以了 //如果=9,那麼該位置零,向倒數第二位+1,同樣判斷是否小於9,小於則直接+1,否則向數組前面進位 //一種極端的情況:比如999,進位後1000,變長了 class Solution { public: vectorplusOne(vector & digits) { vector ans=digits; int i=0; for (i=ans.size()-1; i>=0; i--) //從低位開始遍歷,逆序遍歷 { if(i==0 && ans[0] ==9) {//處理極端情況 ans[i] = 0; vector ::iterator ansiter=ans.begin(); ans.insert ( ansiter, 1); break; } if (ans[i] != 9) { ans[i] += 1; break; } else { ans[i] = 0; } } return ans; } };
骯髒的性能...............................