code第一部分数组:第十六题 数组表示数,加一操作
Given a number represented as an array of digits, plus one to the number.
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <vector> using namespace std; int * addone(int *a,int n) { int *ans; for (int i = n-1; i >=0; i--) { if (a[i]!=9) { a[i]++; break; } else { a[i]=0; } } if (a[0]==0) { ans=(int *)malloc(sizeof(int)*(n+1)); for (int i = n; i >0; i--) { ans[i]=a[i-1]; } ans[0]=1; return ans; } else { return a; } } vector<int> plusOne(vector<int> &digits) { int i; for(i = digits.size() - 1;i >= 0;--i){ if(digits[i] != 9){ digits[i]++; break; } else { digits[i] = 0; } } if(digits[0]==0) { digits.insert(digits.begin(),1); } return digits; } int main() { int a[4]={9,9,9,9}; int len=0; if (a[3]==9) { len=sizeof(a)/sizeof(int)+1; } else { len=sizeof(a)/sizeof(int); } int *b = addone(a,4); for (int i = 0; i < len; i++) { cout<<b[i]; } cout<<endl; vector<int> result; vector<int> array = {1,9,9}; result = plusOne(array); int n = result.size(); for(int i = 0;i < n;i++){ cout<<result[i]; } return 0; }