Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d6a318f

Browse files
ADD Plus-One problem #74
1 parent 396dc81 commit d6a318f

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

‎Easy/plus-one.cs

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
using System.Numerics;
2+
3+
public class Solution
4+
{
5+
#region First Approach
6+
private static BigInteger _ConvertToNumber(int[] digits)
7+
{
8+
if (digits is null || digits.Length == 0)
9+
{
10+
return 0;
11+
}
12+
13+
BigInteger result = 0;
14+
for (int i = 0; i < digits.Length; i++)
15+
{
16+
result = (result * 10) + digits[i];
17+
}
18+
19+
return result;
20+
}
21+
22+
private static int[] _ConvertToArray(BigInteger number)
23+
{
24+
List<int> digits = new();
25+
26+
while (number > 0)
27+
{
28+
byte remainder = (byte)(number % 10);
29+
number /= 10;
30+
31+
digits.Add(remainder);
32+
}
33+
34+
digits.Reverse();
35+
return digits.ToArray();
36+
}
37+
38+
public static int[] PlusOne(int[] digits)
39+
{
40+
if (digits is null || digits.Length == 0)
41+
{
42+
return [];
43+
}
44+
45+
int[] result = [];
46+
47+
BigInteger number = _ConvertToNumber(digits);
48+
number++;
49+
50+
result = _ConvertToArray(number);
51+
52+
return result;
53+
}
54+
#endregion
55+
56+
#region Second Approach
57+
public static int[] PlusOne2(int[] digits)
58+
{
59+
if (digits is null || digits.Length == 0)
60+
{
61+
return [];
62+
}
63+
64+
for (int i = digits.Length - 1; i >= 0; i--)
65+
{
66+
if (digits[i] < 9)
67+
{
68+
digits[i]++;
69+
70+
return digits;
71+
}
72+
73+
digits[i] = 0;
74+
}
75+
76+
int[] result = new int[digits.Length + 1];
77+
78+
result[0] = 1;
79+
80+
return result;
81+
}
82+
#endregion
83+
84+
static void Main()
85+
{
86+
int[] digits = [1, 9, 9, 9];
87+
88+
Console.WriteLine(string.Join(", ", digits));
89+
90+
int[] result = PlusOne(digits);
91+
int[] result2 = PlusOne2(digits);
92+
93+
Console.WriteLine(string.Join(", ", result));
94+
Console.WriteLine(string.Join(", ", result2));
95+
}
96+
}
97+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /