日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode:Plus One

發布時間:2025/7/14 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode:Plus One 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Given 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.

題意:一個非負整數按位存儲于一個int數組中,排列順序為:最高位在array[0] ,最低位在[n-1],例如:18,存儲為:array[0]=1; array[1]=8;

思路:可以從數組的最后一位開始加1,注意需要考慮進位,如果到[0]位之后仍然有進位存在,則需要在數組起始處新開一個位來存儲。

分析:從低位到高位,只有連續遇到9的情況最高位才能加1進位。所以代碼如下:

class
Solution { public:vector<int> plusOne(vector<int>& digits) {int len = digits.size();int i=0;for(i=len-1;i>=0;i--){if(digits[i]<9){digits[i]+=1;break;//只要最低位到最高位有一個低于9就不會產生[0]位之后的進位}else {digits[i]=0;}}
//各位全是9時
if(i==-1){digits.insert(digits.begin(), 1);}return digits;} };

其他解法:(非常容易理解)

class Solution { public:vector<int> plusOne(vector<int>& digits) {int i = digits.size() - 1;//相當于n=digits.size,i=n-1int carray = 1;while(i >= 0){if(carray == 1){int sum = digits[i] + 1;digits[i] = sum % 10;if(sum < 10){carray = 0;break;}}i--;}if(carray == 1){digits.insert(digits.begin(), 1);}return digits;} };

  

轉載于:https://www.cnblogs.com/carsonzhu/p/4557147.html

總結

以上是生活随笔為你收集整理的leetcode:Plus One的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。