FakeStandard

Posted on

Plus One

#66.Plus One

Problem statement

You are given a large integer represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s.

Increment the large integer by one and return the resulting array of digits.

Example 1

``````Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
``````

Example 2

``````Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
``````

Example 3

``````Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
``````

Solution

``````public int[] PlusOne(int[] digits)
{
string str = "";

for (int i = 0; i < digits.Length; i++)
str += digits[i];

int tmp = int.Parse(str) + 1;

str = tmp.ToString();

int[] res = new int[str.Length];

for (int i = 0; i < str.Length; i++)
res[i] = int.Parse(str[i].ToString());

return res;
}
``````

``````public int[] PlusOne(int[] digits)
{
if (digits.Length == 0) return null;

List<int> list = new List<int>();
bool carry = false;

for (int i = digits.Length - 1; i >= 0; i--)
{
if (i == digits.Length - 1)
{
if (digits[i] + 1 == 10)
{
carry = true;
}
else
}
else
{
if (carry)
{
if (digits[i] + 1 == 10)
{
carry = true;
}
else
{
carry = false;
}
}
else

}
}

if (carry)

var res = list.ToArray();

Array.Reverse(res);

return res;
}
``````

``````public int[] PlusOne(int[] digits)
{
List<int> list = new List<int>();
bool carry = false;

int len = digits.Length - 1;

if (digits[len] + 1 == 10)
{
carry = true;
}

for (int i = len - 1; i >= 0; i--)
{
if (carry)
{
if (digits[i] + 1 == 10)
else
{
carry = false;
}
}
}

var res = list.ToArray();
Array.Reverse(res);

return res;
}
``````

Reference

LeetCode Solution

GitHub Repository

Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or click like on my Leetcode solution