<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jet丁Neat Coding on Medium]]></title>
        <description><![CDATA[Stories by Jet丁Neat Coding on Medium]]></description>
        <link>https://medium.com/@neatcoding?source=rss-9a329162b9c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*UOapptskAfJ0jPjUIe3wVg.png</url>
            <title>Stories by Jet丁Neat Coding on Medium</title>
            <link>https://medium.com/@neatcoding?source=rss-9a329162b9c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:53:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@neatcoding/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[LeetCode Move zero elements]]></title>
            <link>https://medium.com/@neatcoding/leetcode-move-zero-elements-310cea5bd7cd?source=rss-9a329162b9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/310cea5bd7cd</guid>
            <dc:creator><![CDATA[Jet丁Neat Coding]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 23:42:35 GMT</pubDate>
            <atom:updated>2020-04-06T00:46:10.993Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>LeetCode30.4 迁移0元素</strong></p><p>Contents</p><p><a href="#_Toc36997310">Javascript. 1</a></p><p><a href="#_Toc36997311">方案：… 1</a></p><p><a href="#_Toc36997312">测试案例：… 2</a></p><p><a href="#_Toc36997313">Go. 3</a></p><p><a href="#_Toc36997314">方案：… 3</a></p><p><a href="#_Toc36997315">使用案例：… 4</a></p><p><a href="#_Toc36997316">Rust. 6</a></p><p><a href="#_Toc36997317">方案：… 6</a></p><p><a href="#_Toc36997318">测试案例：… 7</a></p><p><a href="#_Toc36997319">Kotlin: 8</a></p><p><a href="#_Toc36997320">方案：… 8</a></p><p><a href="#_Toc36997321">测试案例：… 8</a></p><p><a href="#_Toc36997322">Python3: 9</a></p><p><a href="#_Toc36997323">方案：… 9</a></p><p><a href="#_Toc36997324">测试案例：… 10</a></p><p><a href="#_Toc36997325">Java: 11</a></p><p><a href="#_Toc36997326">方案：… 11</a></p><p><a href="#_Toc36997327">测试案例：… 12</a></p><p><a href="#_Toc36997328">C++: 13</a></p><p><a href="#_Toc36997329">方案：… 13</a></p><p><a href="#_Toc36997330">测试案例：… 14</a></p><p><a href="#_Toc36997331">C#: 15</a></p><p><a href="#_Toc36997332">方案：… 15</a></p><p><a href="#_Toc36997333">测试案例：… 16</a></p><p>Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.</p><p><strong>Example:</strong></p><p>Input: [0,1,0,3,12]</p><p>Output: [1,3,12,0,0]</p><p><strong>Note</strong>:</p><p>1. You must do this <strong>in-place</strong> without making a copy of the array.</p><p>2. Minimize the total number of operations.</p><h3>Javascript</h3><h3>方案：</h3><pre>var moveZeroes = function(nums) {<br>    let index = 0;<br>    for (let i = 0; i &lt; nums.length; i ++) {<br>      if(nums[i] != 0) {<br>        nums[index ++] = nums[i];<br>      }<br>    }<br><br>    while(index &lt; nums.length) {<br>        nums[index ++] = 0;<br>    }<br>};</pre><h3>测试案例：</h3><pre>describe(&quot;moveZeroes()&quot;, function () {<br>  it(&quot;test1&quot;, function () {<br>    // 1. ARRANGE<br>    let nums = [0, 1, 0, 3, 12];<br>    let expected = [1, 3, 12, 0, 0];<br><br>    // 2. ACT<br>    moveZeroes(nums);<br><br>    // 3. ASSERT<br>    for (let i = 0; i &lt; nums.length; i++) {<br>      expect(nums[i]).to.be.equal(expected[i]);<br>    }<br>  });<br>  it(&quot;test2&quot;, function () {<br>    // 1. ARRANGE<br>    let nums = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9];<br>    let expected = [1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0];<br><br>    // 2. ACT<br>    moveZeroes(nums);<br>    console.log(nums);<br>    // 3. ASSERT<br>    for (let i = 0; i &lt; nums.length; i++) {<br>      expect(nums[i]).to.be.equal(expected[i]);<br>    }<br>  });<br>});</pre><h3>Go</h3><h3>方案：</h3><pre>func moveZeroes(nums []int) {<br>   index := <em>0<br>   </em>len := len(nums)<br>   for i := <em>0</em>; i &lt; len; i++ {<br>      if nums[i] != <em>0 </em>{<br>         nums[index] = nums[i]<br>         index++<br>      }<br>   }<br>   for index &lt; len {<br>      nums[index] = <em>0<br></em>      index++<br>   }<br>}</pre><h3>使用案例：</h3><pre>func Test_moveZeroes(t *testing.T) {<br>   type args struct {<br>      nums     []int<br>      expected []int<br>   }<br>   tests := []struct {<br>      name string<br>      args args<br>   }{<br>      {&quot;test1&quot;, args{nums: []int{<em>0</em>, <em>1</em>, <em>0</em>, <em>3</em>, <em>12</em>}, expected: []int{<em>1</em>, <em>3</em>, <em>12</em>, <em>0</em>, <em>0</em>}}},<br>      {&quot;test2&quot;, args{nums: []int{<em>1</em>, <em>9</em>, <em>8</em>, <em>4</em>, <em>0</em>, <em>0</em>, <em>2</em>, <em>7</em>, <em>0</em>, <em>6</em>, <em>0</em>, <em>9</em>}, expected: []int{<em>1</em>, <em>9</em>, <em>8</em>, <em>4</em>, <em>2</em>, <em>7</em>, <em>6</em>, <em>9</em>, <em>0</em>, <em>0</em>, <em>0</em>, <em>0</em>}}},<br>   }<br>   for _, tt := range tests {<br>      t.Run(tt.name, func(t *testing.T) {<br>         moveZeroes(tt.args.nums)<br>         len := len(tt.args.nums)<br>         for i := <em>0</em>; i &lt; len; i++ {<br>            if tt.args.nums[i] != tt.args.expected[i] {<br>               t.Errorf(&quot;actual = <em>%v</em>, want <em>%v</em>&quot;, tt.args.nums[i], tt.args.expected[i])<br>            }<br>         }<br>      })<br>   }<br>}</pre><h3>Rust</h3><h3>方案：</h3><pre>impl Solution {<br>    pub fn move_zeroes(nums: &amp;mut Vec&lt;i32&gt;) {<br>        let mut index = 0;<br>        let len = nums.len();<br>        for i in 0..len {<br>           if nums[i] != 0 {<br>               nums[index] = nums[i];<br>               index +=1;<br>           }<br>        }<br>        while index &lt; len  {<br>            nums[index] = 0;<br>            index +=1;<br>        }<br>    }<br>}</pre><h3>测试案例：</h3><pre>#[test]<br>fn test1() {<br>    let mut vec: Vec&lt;i32&gt; = vec![0, 1, 0, 3, 12];<br>    let expected = vec![1, 3, 12, 0, 0];<br><br>    Solution::move_zeroes(&amp;mut vec);<br>    let len = vec.len();<br>    for i in 0..len {<br>        assert_eq!(vec[i], expected[i]);<br>    }<br>   <br>}<br><br>#[test]<br>fn test2() {<br>    let mut vec: Vec&lt;i32&gt; = vec![1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9];<br>    let expected = vec![1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0];<br>    let len = vec.len();<br>    Solution::move_zeroes(&amp;mut vec);<br>    <br>    for i in 0..len {<br>        assert_eq!(vec[i], expected[i]);<br>    }<br>}</pre><h3>Kotlin:</h3><h3>方案：</h3><pre>class Solution {<br>    fun moveZeroes(nums: IntArray) {<br>        var index = 0<br>        for (i in nums.indices) {<br>            if (nums[i] != 0) {<br>                nums[index++] = nums[i]<br>            }<br>        }<br>        while (index &lt; nums.size) {<br>            nums[index++] = 0<br>        }<br>    }<br>}</pre><h3>测试案例：</h3><pre>@Test<br>fun test1() {<br>    val solution = Solution()<br>    val nums = intArrayOf(0, 1, 0, 3, 12)<br>    solution.moveZeroes(nums)<br>    val expected = intArrayOf(1, 3, 12, 0, 0)<br>    for (i in nums.indices) {<br>        Assert.assertEquals(nums[i], expected[i])<br>    }<br>}<br><br>@Test<br>fun test2() {<br>    val solution = Solution()<br>    val nums = intArrayOf(1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9)<br>    solution.moveZeroes(nums)<br>    val expected = intArrayOf(1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0)<br>    for (i in nums.indices) {<br>        Assert.assertEquals(nums[i], expected[i])<br>    }<br>}</pre><h3>Python3:</h3><h3>方案：</h3><pre>class Solution:<br>    def moveZeroes(self, nums: List[int]) -&gt; None:<br>        size = len(nums)<br>        index = 0<br>        for i in range(0, size):<br>            if(nums[i] != 0) :<br>                nums[index] = nums[i]<br>                index = index + 1<br>        while(index &lt; size): <br>            nums[index] = 0<br>            index = index + 1</pre><h3>测试案例：</h3><pre>def test1(self):<br>    s = Solution()<br>    a = [0, 1, 0, 3, 12] <br>    e = [1, 3, 12, 0, 0] <br>    s.moveZeroes(a)<br>    size = len(a)<br>    for i in range(0, size):<br>        self.assertEqual(a[i], e[i] )<br>def test2(self):<br>    s = Solution()<br>    a = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9] <br>    e = [1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0] <br>    s.moveZeroes(a)<br>    size = len(a)<br>    for i in range(0, size):<br>        self.assertEqual(a[i], e[i] )</pre><h3>Java:</h3><h3>方案：</h3><pre>class Solution {<br>    public void moveZeroes(int[] nums) {<br>        int index = 0;<br>        for (int i = 0; i &lt; nums.length; i++) {<br>            if (nums[i] != 0) {<br>                nums[index++] = nums[i];<br>            }<br>        }<br>        while (index &lt; nums.length) {<br>            nums[index++] = 0;<br>        }<br>    }<br>}</pre><h3>测试案例：</h3><pre>@Test<br>public void test1() {<br>    Solution solution = new Solution();<br>    int[] nums = { 0, 1, 0, 3, 12 };<br>    solution.moveZeroes(nums);<br>    int[] expected = { 1, 3, 12, 0, 0 };<br>    for (int i = 0; i &lt; nums.length; i++)<br>    {<br>        Assert.assertEquals(nums[i], expected[i]);<br>    }<br>}<br><br>@Test<br>public void test2() {<br>    Solution solution = new Solution();<br>    int[] nums = { 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 };<br>    solution.moveZeroes(nums);<br>    int[] expected = { 1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0 };<br>    for (int i = 0; i &lt; nums.length; i++)<br>    {<br>        Assert.assertEquals(nums[i], expected[i]);<br>    }<br>}</pre><h3>C++:</h3><h3>方案：</h3><pre>class Solution<br>{<br>public:<br>    void moveZeroes(vector&lt;int&gt;&amp; nums) {<br>        int index = 0;<br>        for (int i = 0; i &lt; nums.size(); i++) {<br>            if (nums[i] != 0) {<br>                nums[index++] = nums[i];<br>            }<br>        }<br>        while (index &lt; nums.size()) {<br>            nums[index++] = 0;<br>        }<br>    }<br>};</pre><h3>测试案例：</h3><pre>TEST_METHOD(TestMethod1) {<br>   Solution solution;<br>   int numsArray[] = { 0, 1, 0, 3, 12 };<br>   vector&lt;int&gt; nums;<br>   nums.insert(nums.begin(), std::begin(numsArray), std::end(numsArray));<br>   solution.moveZeroes(nums);<br>   int expected[] = { 1, 3, 12, 0, 0 };<br>   for (int i = 0; i &lt; nums.size(); i++) {<br>      Assert::AreEqual(nums[i], expected[i]);<br>   }<br>}<br><br>TEST_METHOD(TestMethod2)<br>{<br>   Solution solution;<br>   int numsArray[] = { 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 };<br>   vector&lt;int&gt; nums;<br>   nums.insert(nums.begin(), std::begin(numsArray), std::end(numsArray));<br>   solution.moveZeroes(nums);<br>   int expected[] = { 1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0 };<br>   for (int i = 0; i &lt; nums.size(); i++) {<br>      Assert::AreEqual(nums[i], expected[i]);<br>   }<br>}</pre><h3>C#:</h3><h3>方案：</h3><pre>public class Solution<br>{<br>    public void moveZeroes(int[] nums)<br>    {<br>        int index = 0;<br>        for(int i = 0; i &lt; nums.Length; i ++ )<br>        {<br>            if(nums[i] != 0)<br>            {<br>                nums[index++] = nums[i];<br>            }<br>        }<br>        while(index &lt; nums.Length)<br>        {<br>            nums[index++] = 0;<br>        }<br>    }<br>}</pre><h3>测试案例：</h3><pre>[TestMethod()]<br>public void Test1()<br>{<br>    Solution solution = new Solution();<br>    int[] nums = { 0, 1, 0, 3, 12 };<br>    solution.moveZeroes(nums);<br>    int[] expected = { 1, 3, 12, 0, 0 };<br>    for (int i = 0; i &lt; nums.Length; i++)<br>    {<br>        Assert.AreEqual(nums[i], expected[i]);<br>    }<br>}<br><br>[TestMethod()]<br>public void Test2()<br>{<br>    Solution solution = new Solution();<br>    int[] nums = { 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 };<br>    solution.moveZeroes(nums);<br>    int[] expected = { 1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0 };<br>    for (int i = 0; i &lt; nums.Length; i++)<br>    {<br>        Assert.AreEqual(nums[i], expected[i]);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=310cea5bd7cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Subarray with max sum]]></title>
            <link>https://medium.com/@neatcoding/leetcode-subarray-with-max-sum-62c759989307?source=rss-9a329162b9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/62c759989307</guid>
            <dc:creator><![CDATA[Jet丁Neat Coding]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 23:40:41 GMT</pubDate>
            <atom:updated>2020-04-06T00:41:03.614Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode Subarray with the max sum</h3><p><strong>LeetCode 最大子数组</strong></p><p>Contents</p><p><a href="#_Toc36997186">Javascript. 1</a></p><p><a href="#_Toc36997187">方案：… 1</a></p><p><a href="#_Toc36997188">测试案例：… 2</a></p><p><a href="#_Toc36997189">Go. 3</a></p><p><a href="#_Toc36997190">方案：… 3</a></p><p><a href="#_Toc36997191">使用案例：… 4</a></p><p><a href="#_Toc36997192">Rust. 5</a></p><p><a href="#_Toc36997193">方案：… 5</a></p><p><a href="#_Toc36997194">测试案例：… 6</a></p><p><a href="#_Toc36997195">Kotlin: 7</a></p><p><a href="#_Toc36997196">方案：… 7</a></p><p><a href="#_Toc36997197">测试案例：… 7</a></p><p><a href="#_Toc36997198">Python3: 8</a></p><p><a href="#_Toc36997199">方案：… 8</a></p><p><a href="#_Toc36997200">测试案例：… 9</a></p><p><a href="#_Toc36997201">Java: 10</a></p><p><a href="#_Toc36997202">方案：… 10</a></p><p><a href="#_Toc36997203">测试案例：… 10</a></p><p><a href="#_Toc36997204">C++: 12</a></p><p><a href="#_Toc36997205">方案：… 12</a></p><p><a href="#_Toc36997206">测试案例：… 13</a></p><p><a href="#_Toc36997207">C#: 14</a></p><p><a href="#_Toc36997208">方案：… 14</a></p><p><a href="#_Toc36997209">测试案例：… 15</a></p><p>Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.</p><p><strong>Example:</strong></p><pre>Input: [-2,1,-3,4,-1,2,1,-5,4],</pre><pre>Output: 6</pre><pre>Explanation: [4,-1,2,1] has the largest sum = 6.</pre><h3>Javascript</h3><h3>方案：</h3><pre>var maxSubArray = function(nums) {<br>    let result = nums[0];<br>    let temp = nums[0];<br>    for (let i = 1; i &lt; nums.length; i ++) {<br>        temp = Math.max(nums[i], nums[i] + temp);<br>        result = Math.max(temp, result);<br>    }<br><br>    return result;<br>};</pre><h3>测试案例：</h3><pre>describe(&quot;maxSubArray()&quot;, function () {<br>  it(&quot;test1&quot;, function () {<br>    // 1. ARRANGE<br>    let nums = [-2, -3, 4, -1, -2, 1, 5, -3];<br><br>    // 2. ACT<br>    var result = maxSubArray(nums);<br><br>    // 3. ASSERT<br>    expect(result).to.be.equal(7);<br>  });<br><br>  it(&quot;test2&quot;, function () {<br>    // 1. ARRANGE<br>    let nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4];<br><br>    // 2. ACT<br>    var result = maxSubArray(nums);<br><br>    // 3. ASSERT<br>    expect(result).to.be.equal(6);<br>  });<br><br>  it(&quot;test3&quot;, function () {<br>    // 1. ARRANGE<br>    let nums = [-2];<br><br>    // 2. ACT<br>    var result = maxSubArray(nums);<br><br>    // 3. ASSERT<br>    expect(result).to.be.equal(-2);<br>  });<br>});</pre><h3>Go</h3><h3>方案：</h3><pre>func maxSubArray(nums []int) int {<br>   result := nums[<em>0</em>]<br>   temp := nums[<em>0</em>]<br>   for i := <em>1</em>; i &lt; len(nums); i++ {<br>      temp = int(math.Max(float64(nums[i]), float64(nums[i]+temp)))<br>      result = int(math.Max(float64(temp), float64(result)))<br>   }<br>   return result<br>}</pre><h3>使用案例：</h3><pre>func Test_maxSubArray(t *testing.T) {<br>   type args struct {<br>      nums []int<br>   }<br>   tests := []struct {<br>      name string<br>      args args<br>      want int<br>   }{<br>      {&quot;test1&quot;, args{nums: []int{-<em>2</em>, -<em>3</em>, <em>4</em>, -<em>1</em>, -<em>2</em>, <em>1</em>, <em>5</em>, -<em>3</em>}}, <em>7</em>},<br>      {&quot;test2&quot;, args{nums: []int{-<em>2</em>, <em>1</em>, -<em>3</em>, <em>4</em>, -<em>1</em>, <em>2</em>, <em>1</em>, -<em>5</em>, <em>4</em>}}, <em>6</em>},<br>      {&quot;test3&quot;, args{nums: []int{-<em>2</em>}}, -<em>2</em>},<br>   }<br>   for _, tt := range tests {<br>      t.Run(tt.name, func(t *testing.T) {<br>         if got := maxSubArray(tt.args.nums); got != tt.want {<br>            t.Errorf(&quot;maxSubArray() = <em>%v</em>, want <em>%v</em>&quot;, got, tt.want)<br>         }<br>      })<br>   }<br>}</pre><h3>Rust</h3><h3>方案：</h3><pre>impl Solution {<br>    pub fn max_sub_array(nums: Vec&lt;i32&gt;) -&gt; i32 {<br>        let mut result = nums[0]; <br>        let mut temp = nums[0]; <br>        for (_pos, e) in nums.iter().enumerate() {<br>           temp = std::cmp::max(*e, *e + temp);<br>           result = std::cmp::max(temp, result);<br>        }<br>        return result;        <br>    }<br>}</pre><h3>测试案例：</h3><pre>#[test]<br>fn test1() {<br>    let vec = vec![-2, -3, 4, -1, -2, 1, 5, -3];<br>    let result = Solution::max_sub_array(vec);<br>    assert_eq!(result, 7);<br>}<br><br>#[test]<br>fn test2() {<br>    let vec = vec![-2, 1, -3, 4, -1, 2, 1, -5, 4];<br>    let result = Solution::max_sub_array(vec);<br>    assert_eq!(result, 6);<br>}<br>#[test]<br>fn test3() {<br>    let vec = vec![-2];<br>    let result = Solution::max_sub_array(vec);<br>    assert_eq!(result, -2);<br>}</pre><h3>Kotlin:</h3><h3>方案：</h3><pre><strong>internal class </strong>Solution {</pre><pre>    <strong>fun </strong>maxSubArray(nums: IntArray): Int {</pre><pre>        <strong>var </strong>result = nums[0]</pre><pre>        <strong>var </strong>temp = nums[0]</pre><pre>        <strong>for </strong>(i <strong>in </strong>1 <em>until </em>nums.<strong>size</strong>) {</pre><pre>            temp = Math.max(nums[i] + temp, nums[i])</pre><pre>            result = Math.max(result, temp)</pre><pre>        }</pre><pre>        <strong>return </strong>result</pre><pre>    }</pre><pre>}</pre><h3>测试案例：</h3><pre>@Test</pre><pre><strong>fun </strong>test1() {</pre><pre>    <strong>val </strong>solution = Solution()</pre><pre>    <strong>val </strong>nums = <em>intArrayOf</em>(-2)</pre><pre>    <strong>val </strong>result = solution.maxSubArray(nums)</pre><pre>    Assert.assertEquals(result, -2)</pre><pre>}</pre><pre>@Test</pre><pre><strong>fun </strong>test2() {</pre><pre>    <strong>val </strong>solution = Solution()</pre><pre>    <strong>val </strong>nums = <em>intArrayOf</em>(-2, -3, 4, -1, -2, 1, 5, -3)</pre><pre>    <strong>val </strong>result = solution.maxSubArray(nums)</pre><pre>    Assert.assertEquals(result, 7)</pre><pre>}</pre><pre>@Test</pre><pre><strong>fun </strong>test3() {</pre><pre>    <strong>val </strong>solution = Solution()</pre><pre>    <strong>val </strong>nums = <em>intArrayOf</em>(-2,1,-3,4,-1,2,1,-5,4)</pre><pre>    <strong>val </strong>result = solution.maxSubArray(nums)</pre><pre>    Assert.assertEquals(result, 6)</pre><pre>}</pre><h3>Python3:</h3><h3>方案：</h3><pre>class Solution:<br>    def maxSubArray(self, nums: List[int]) -&gt; int:<br>        result= nums[0]<br>        temp = nums[0]<br>        size = len(nums)<br><br>        for i in range(1, size):<br>            temp = max(temp + nums[i], nums[i])<br>            result = max(temp, result)<br><br>        return result</pre><h3>测试案例：</h3><pre>def test_maxSubArray1(self):<br>    s = Solution()<br>    a = [-2, -3, 4, -1, -2, 1, 5, -3] <br>    self.assertEqual(s.maxSubArray(a), 7 )<br>def test_maxSubArray2(self):<br>    s = Solution()<br>    a = [-2,1,-3,4,-1,2,1,-5,4] <br>    self.assertEqual(s.maxSubArray(a), 6 )    <br><br>def test_maxSubArray3(self):<br>    s = Solution()<br>    a = [-2] <br>    self.assertEqual(s.maxSubArray(a), -2 )</pre><h3>Java:</h3><h3>方案：</h3><pre>class Solution {<br>    public int maxSubArray(int[] nums) {<br>        int result = nums[0];<br>        int temp = nums[0];<br><br>        for (int i = 1; i &lt; nums.length; i++) {<br>            temp = Math.max(nums[i], temp + nums[i]);<br>            result = Math.max(temp, result);<br>        }<br>        return result;<br>    }<br>}</pre><h3>测试案例：</h3><pre>@Test<br>public void test1() {<br>    Solution solution = new Solution(); <br>    int nums[] = {-2, -3, 4, -1, -2, 1, 5, -3};<br>    int result = solution.maxSubArray(nums);<br>    Assert.assertEquals(result, 7);<br>}<br><br><br>@Test<br>public void test2() {<br>    Solution solution = new Solution(); <br>    int nums[] = {-2,1,-3,4,-1,2,1,-5,4};<br>    int result = solution.maxSubArray(nums);<br>    Assert.assertEquals(result, 6);<br>}<br><br><br>@Test<br>public void test3() {<br>    Solution solution = new Solution(); <br>    int nums[] = {-2};<br>    int result = solution.maxSubArray(nums);<br>    Assert.assertEquals(result, -2);<br>}</pre><h3>C++:</h3><h3>方案：</h3><pre>class Solution<br>{<br>public:<br>    int maxSubArray(vector&lt;int&gt; &amp;nums)<br>    {<br>        int result = nums[0];<br>        int temp = nums[0];<br><br>        for (int i = 1; i &lt; nums.size(); i++)<br>        {<br>            temp = max(nums[i], temp + nums[i]);<br>            result = max(result, temp);<br>        }<br>        return result;<br>    }<br>};</pre><h3>测试案例：</h3><pre>TEST_METHOD(TestMethod1) {<br>   Solution solution;<br>   int numsArray[] = { -2, -3, 4, -1, -2, 1, 5, -3 };<br>   vector&lt;int&gt; nums;<br>   nums.insert(nums.begin(), std::begin(numsArray), std::end(numsArray));<br>   Assert::AreEqual(7, solution.maxSubArray(nums));<br>} // namespace UnitTest1<br><br>TEST_METHOD(TestMethod2)<br>{<br>   int numsArray[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };<br>   vector&lt;int&gt; nums;<br>   nums.insert(nums.begin(), std::begin(numsArray), std::end(numsArray));<br>   Solution solution;<br>   Assert::AreEqual(6, solution.maxSubArray(nums));<br>}<br><br>TEST_METHOD(TestMethod3)<br>{<br>   int numsArray[] = { -2 };<br>   vector&lt;int&gt; nums;<br>   nums.insert(nums.begin(), std::begin(numsArray), std::end(numsArray));<br>   Solution solution;<br>   Assert::AreEqual(-2, solution.maxSubArray(nums));<br>}</pre><h3>C#:</h3><h3>方案：</h3><pre>public class Solution<br>{<br>    public int MaxSubArray(int[] nums)<br>    {<br>        int result = nums[0];<br>        int temp = nums[0];<br>        for(int i = 1; i &lt; nums.Length; i ++)<br>        {<br>            temp = Math.Max(nums[i], nums[i] + temp);<br>            result = Math.Max(temp, result);<br>        }<br>        return result;<br>    }<br>}</pre><h3>测试案例：</h3><pre>[TestMethod()]<br>public void Test1()<br>{<br>    Solution solution = new Solution();<br>    int[] nums = { -2, -3, 4, -1, -2, 1, 5, -3 };<br>    int result = solution.MaxSubArray(nums);<br>    Assert.AreEqual(7, result);<br>}<br><br>[TestMethod()]<br>public void Test2()<br>{<br>    Solution solution = new Solution();<br>    int[] nums = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };<br>    int result = solution.MaxSubArray(nums);<br>    Assert.AreEqual(6, result);<br>}<br><br>[TestMethod()]<br>public void Test3()<br>{<br>    Solution solution = new Solution();<br>    int[] nums = { -2 };<br>    int result = solution.MaxSubArray(nums);<br>    Assert.AreEqual(-2, result);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62c759989307" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Happy number]]></title>
            <link>https://medium.com/@neatcoding/leetcode-happy-number-47afc7e80a73?source=rss-9a329162b9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/47afc7e80a73</guid>
            <dc:creator><![CDATA[Jet丁Neat Coding]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 23:39:05 GMT</pubDate>
            <atom:updated>2020-04-06T00:36:01.911Z</atom:updated>
            <content:encoded><![CDATA[<p>LeetCode 幸福数字</p><p>Contents</p><p><a href="#_Toc36997077">Javascript. 1</a></p><p><a href="#_Toc36997078">方案：… 1</a></p><p><a href="#_Toc36997079">测试案例：… 2</a></p><p><a href="#_Toc36997080">Go. 4</a></p><p><a href="#_Toc36997081">方案：… 4</a></p><p><a href="#_Toc36997082">使用案例：… 5</a></p><p><a href="#_Toc36997083">Rust. 6</a></p><p><a href="#_Toc36997084">方案：… 6</a></p><p><a href="#_Toc36997085">测试案例：… 7</a></p><p><a href="#_Toc36997086">Kotlin: 8</a></p><p><a href="#_Toc36997087">方案：… 8</a></p><p><a href="#_Toc36997088">测试案例：… 8</a></p><p><a href="#_Toc36997089">Python3: 9</a></p><p><a href="#_Toc36997090">方案：… 9</a></p><p><a href="#_Toc36997091">测试案例：… 10</a></p><p><a href="#_Toc36997092">Java: 10</a></p><p><a href="#_Toc36997093">方案：… 10</a></p><p><a href="#_Toc36997094">测试案例：… 11</a></p><p><a href="#_Toc36997095">C++: 12</a></p><p><a href="#_Toc36997096">方案：… 12</a></p><p><a href="#_Toc36997097">测试案例：… 13</a></p><p><a href="#_Toc36997098">C#: 14</a></p><p><a href="#_Toc36997099">方案：… 14</a></p><p><a href="#_Toc36997100">测试案例：… 15</a></p><p>Write an algorithm to determine if a number is “happy”.</p><p>A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.</p><p><strong>Example:</strong></p><p>Input: 19</p><p>Output: true</p><p>Explanation:</p><p>12 + 92 = 82</p><p>82 + 22 = 68</p><p>62 + 82 = 100</p><p>12 + 02 + 02 = 1</p><h3>Javascript</h3><h3>方案：</h3><pre>var isHappy = function (n) {<br>  let set = new Set();<br>  while (!set.has(n)) {<br>    set.add(n);<br>    let v = 0;<br>    while (n &gt; 0) {<br>      v += Math.pow(n % 10, 2);<br>      n = Math.floor(n / 10);<br>    }<br>    n = v;<br>  }<br>  return n == 1;<br>};</pre><h3>测试案例：</h3><pre>describe(&quot;isHappy()&quot;, function () {<br>  it(&quot;test1&quot;, function () {<br>    // 1. ARRANGE<br>    let num = 19;<br><br>    // 2. ACT<br>    var result = isHappy(num);<br><br>    // 3. ASSERT<br>    expect(result).to.be.equal(true);<br>  });<br><br>  it(&quot;test2&quot;, function () {<br>    // 1. ARRANGE<br>    let num = 4;<br><br>    // 2. ACT<br>    var result = isHappy(num);<br><br>    // 3. ASSERT<br>    expect(result).to.be.equal(false);<br>  });<br><br>  it(&quot;test3&quot;, function () {<br>    // 1. ARRANGE<br>    let num = 123;<br><br>    // 2. ACT<br>    var result = isHappy(num);<br><br>    // 3. ASSERT<br>    expect(result).to.be.equal(false);<br>  });<br>});</pre><h3>Go</h3><h3>方案：</h3><pre>func isHappy(n int) bool {<br>   m := make(map[int]bool)<br>   ok := <em>false<br>   </em>for !ok {<br>      m[n] = <em>true<br>      </em>v := <em>0<br>      </em>for n &gt; <em>0 </em>{<br>         v += int(math.Pow(float64(n%<em>10</em>), <em>2</em>))<br>         n /= <em>10<br>      </em>}<br>      n = v<br>      _, ok = m[n]<br>   }<br>   return n == <em>1<br></em>}</pre><h3>使用案例：</h3><pre>func Test_isHappy(t *testing.T) {<br>   type args struct {<br>      n int<br>   }<br>   tests := []struct {<br>      name string<br>      args args<br>      want bool<br>   }{<br>      {&quot;test1&quot;, args{n: <em>19</em>}, <em>true</em>},<br>      {&quot;test2&quot;, args{n: <em>4</em>}, <em>false</em>},<br>      {&quot;test3&quot;, args{n: <em>123</em>}, <em>false</em>},<br>   }<br>   for _, tt := range tests {<br>      t.Run(tt.name, func(t *testing.T) {<br>         if got := isHappy(tt.args.n); got != tt.want {<br>            t.Errorf(&quot;isHappy() = <em>%v</em>, want <em>%v</em>&quot;, got, tt.want)<br>         }<br>      })<br>   }<br>}</pre><h3>Rust</h3><h3>方案：</h3><pre>impl Solution {<br>    pub fn is_happy(n: i32) -&gt; bool {<br>        let mut hs = std::collections::HashSet::new();<br>        let mut t = n;<br>        while !hs.contains(&amp;t) {<br>            hs.insert(t);<br>            let mut v = 0;<br>            while t &gt; 0 {<br>                v += i32::pow(t % 10, 2);<br>                t /= 10;<br>                println!(&quot;{0} {1}&quot;, t, v);<br>            }<br>            t = v;<br>        }<br>        return t == 1;<br>    }<br>}</pre><h3>测试案例：</h3><pre>#[test]<br>fn test1() {<br>    let result = Solution::is_happy(19);<br>    assert_eq!(result, true);<br>}<br><br>#[test]<br>fn test2() {<br>    let result = Solution::is_happy(4);<br>    assert_eq!(result, false);<br>}<br>#[test]<br>fn test3() {<br>    let result = Solution::is_happy(123);<br>    assert_eq!(result, false);<br>}</pre><h3>Kotlin:</h3><h3>方案：</h3><pre><strong>internal class </strong>Solution {</pre><pre>    <strong>fun </strong>isHappy(n: Int): Boolean {</pre><pre>        <strong>var </strong>temp = n</pre><pre>        <strong>val </strong>set: MutableSet&lt;Int&gt; = HashSet()</pre><pre>        <strong>while </strong>(set.add(temp)) {</pre><pre>            <strong>var </strong>value = 0</pre><pre>            <strong>while </strong>(temp &gt; 0) {</pre><pre>                value += Math.pow(temp % 10.toDouble(), 2.0).toInt()</pre><pre>                temp /= 10</pre><pre>            }</pre><pre>            temp = value</pre><pre>        }</pre><pre>        <strong>return </strong>temp == 1</pre><pre>    }</pre><pre>}</pre><h3>测试案例：</h3><pre>@Test</pre><pre>fun test1() {</pre><pre>val solution = Solution()</pre><pre>val result = solution.isHappy(19)</pre><pre>Assert.assertEquals(result, true)</pre><pre>}</pre><pre>@Test</pre><pre>fun test2() {</pre><pre>val solution = Solution()</pre><pre>val result = solution.isHappy(4)</pre><pre>Assert.assertEquals(result, false)</pre><pre>}</pre><pre>@Test</pre><pre>fun test3() {</pre><pre>val solution = Solution()</pre><pre>val result = solution.isHappy(123)</pre><pre>Assert.assertEquals(result, false)</pre><pre>}</pre><h3>Python3:</h3><h3>方案：</h3><pre>class Solution:<br>    def isHappy(self, n: int) -&gt; bool:<br>        s = set()<br>        while(n not in s):<br>            s.add(n)<br>            v = 0<br>            while (n &gt; 0):<br>                v += pow(n % 10, 2)<br>                n = n // 10<br>            n = v  <br>        return n == 1</pre><h3>测试案例：</h3><pre>def test_isHappy(self):<br>    s = Solution()<br>    self.assertEqual(s.isHappy(19), True )<br>def test2_isHappy(self):<br>    s = Solution()<br>    self.assertEqual(s.isHappy((4)), False)<br>def test3_isHappy(self):<br>    s = Solution()<br>    self.assertEqual(s.isHappy((123)), False)</pre><h3>Java:</h3><h3>方案：</h3><pre>class Solution {<br><br>    public boolean isHappy(int n) {<br>        Set&lt;Integer&gt; set = new HashSet&lt;Integer&gt;();<br><br>        while (set.add(n))<br>        {<br>            int value = 0;<br>            while (n &gt; 0)<br>            {<br>                value += Math.pow(n % 10, 2);<br>                n /= 10;<br>            }<br>            n = value;<br>        }<br><br>        return n == 1;<br>    }<br>}</pre><h3>测试案例：</h3><pre>@Test<br>public void test1() {<br>    Solution solution = new Solution(); <br>    boolean result = solution.isHappy(19);<br>    Assert.assertEquals(result, true);<br>}<br><br>@Test<br>public void test2() {<br>    Solution solution = new Solution(); <br>    boolean result = solution.isHappy(4);<br>    Assert.assertEquals(result, false);<br>}<br><br>@Test<br>public void test3() {<br>    Solution solution = new Solution(); <br>    boolean result = solution.isHappy(123);<br>    Assert.assertEquals(result, false);<br>}</pre><h3>C++:</h3><h3>方案：</h3><pre>class HappyNumber {<br>public:<br>    bool isHappy(int n) {<br>        unordered_set&lt;int&gt;  set;<br>        while (set.find(n) == set.end())<br>        {<br>            set.insert(n);<br>            int value = 0;<br>            while (n &gt; 0)<br>            {<br>                value += pow(n % 10, 2);<br>                n /= 10;<br>            }<br>            n = value;<br>        }<br><br>        return n == 1;<br>    }<br>};</pre><h3>测试案例：</h3><pre>TEST_METHOD(TestMethod1)<br>{<br>   HappyNumber happyNumber;<br>   Assert::AreEqual(true, happyNumber.isHappy(19));<br>}<br><br>TEST_METHOD(TestMethod2)<br>{<br>   HappyNumber happyNumber;<br>   Assert::AreEqual(false, happyNumber.isHappy(4));<br>}<br><br>TEST_METHOD(TestMethod3)<br>{<br>   HappyNumber happyNumber;<br>   Assert::AreEqual(false, happyNumber.isHappy(123));<br>}</pre><h3>C#:</h3><h3>方案：</h3><pre>public class Solution<br>{<br>    public bool IsHappy(int n)<br>    {<br>        HashSet&lt;int&gt; hs = new HashSet&lt;int&gt;();<br>        while(!hs.Contains(n))<br>        {<br>            hs.Add(n);<br>            int v = 0;<br>            while(n&gt;0)<br>            {<br>                v += (int)Math.Pow(n % 10, 2);<br>                n /= 10;<br>            }<br>            n = v;<br>        }<br><br>        return n == 1;<br>    }<br>}</pre><h3>测试案例：</h3><pre>[TestMethod()]<br>    public void Test1()<br>    {<br>        Solution solution = new Solution();<br>        Assert.AreEqual(true, solution.IsHappy(19));<br>    }<br><br>    [TestMethod()]<br>    public void Test2()<br>    {<br>        Solution solution = new Solution();<br>        Assert.AreEqual(false, solution.IsHappy(4));<br>    }<br><br>    [TestMethod()]<br>    public void Test3()<br>    {<br>        Solution solution = new Solution();<br>        Assert.AreEqual(false, solution.IsHappy(123));<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47afc7e80a73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Single Number]]></title>
            <link>https://medium.com/@neatcoding/leetcode-single-number-c0110d5c4280?source=rss-9a329162b9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0110d5c4280</guid>
            <dc:creator><![CDATA[Jet丁Neat Coding]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 20:10:20 GMT</pubDate>
            <atom:updated>2020-04-06T00:30:26.325Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode 找到单一数字</h3><p>Contents</p><p><a href="#_Toc36998675">Javascript. 2</a></p><p><a href="#_Toc36998676">方案1：… 2</a></p><p><a href="#_Toc36998677">方案2：… 2</a></p><p><a href="#_Toc36998678">测试案例：… 3</a></p><p><a href="#_Toc36998679">Go. 3</a></p><p><a href="#_Toc36998680">方案1：… 4</a></p><p><a href="#_Toc36998681">方案2：… 4</a></p><p><a href="#_Toc36998682">使用案例：… 4</a></p><p><a href="#_Toc36998683">Rust. 5</a></p><p><a href="#_Toc36998684">方案1：… 5</a></p><p><a href="#_Toc36998685">方案2：… 5</a></p><p><a href="#_Toc36998686">测试案例：… 6</a></p><p><a href="#_Toc36998687">Kotlin: 6</a></p><p><a href="#_Toc36998688">方案1：… 6</a></p><p><a href="#_Toc36998689">方案2：… 7</a></p><p><a href="#_Toc36998690">测试案例：… 7</a></p><p><a href="#_Toc36998691">Python3: 8</a></p><p><a href="#_Toc36998692">方案1：… 8</a></p><p><a href="#_Toc36998693">方案2：… 8</a></p><p><a href="#_Toc36998694">测试案例：… 8</a></p><p><a href="#_Toc36998695">Java: 9</a></p><p><a href="#_Toc36998696">方案1：… 9</a></p><p><a href="#_Toc36998697">方案2：… 9</a></p><p><a href="#_Toc36998698">测试案例：… 10</a></p><p><a href="#_Toc36998699">C++: 10</a></p><p><a href="#_Toc36998700">方案1：… 10</a></p><p><a href="#_Toc36998701">方案2：… 11</a></p><p><a href="#_Toc36998702">测试案例：… 11</a></p><p><a href="#_Toc36998703">C#: 12</a></p><p><a href="#_Toc36998704">方案1：… 12</a></p><p><a href="#_Toc36998705">测试案例：… 13</a></p><p>Given a <strong>non-empty</strong> array of integers, every element appears <em>twice</em> except for one. Find that single one.</p><p><strong>Note:</strong></p><p>Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?</p><p><strong>Example 1:</strong></p><p>Input: [2,2,1]</p><p>Output: 1</p><p><strong>Example 2:</strong></p><p>Input: [4,1,2,1,2]</p><p>Output: 4</p><h3>Javascript</h3><h3>方案1：</h3><pre>var singleNumber = function(nums) {<br>    let result = nums[0];<br>    for(let i = 1; i &lt; nums.length; i ++) {<br>        result ^= nums[i];<br>    }<br>    return result;<br>};</pre><h3>方案2：</h3><pre>var singleNumber = function(nums) {<br>    let set = Set();<br>    for(let i = 0; i &lt; nums.length; i ++) {<br>        if(set.has(nums[i])) {<br>            set.delete(nums[i]);<br>        }<br>        else {<br>            set.add(nums[i]);<br>        }<br>    }<br>    for (let item of set)  {<br>        return item;<br>    }<br>    return 0;<br>};</pre><h3>测试案例：</h3><pre>describe(&quot;singleNumber()&quot;, function () {<br>  it(&quot;test1&quot;, function () {<br>    // 1. ARRANGE<br>    let nums = [2, 2, 1];<br><br>    // 2. ACT<br>    var result = singleNumber(nums);<br><br>    // 3. ASSERT<br>    expect(result).to.be.equal(1);<br>  });<br><br>  it(&quot;test2&quot;, function () {<br>    // 1. ARRANGE<br>    let nums = [4, 1, 2, 1, 2];<br><br>    // 2. ACT<br>    var result = singleNumber(nums);<br><br>    // 3. ASSERT<br>    expect(result).to.be.equal(4);<br>  });<br><br>});</pre><h3>Go</h3><h3>方案1：</h3><pre>func singleNumber(nums []int) int {<br>   result := nums[<em>0</em>]<br>   for i := <em>1</em>; i &lt; len(nums); i++ {<br>      result = result ^ nums[i]<br>   }<br>   return result<br>}</pre><h3>方案2：</h3><pre>func singleNumber(nums []int) int {<br>   m := make(map[int]int)<br>   for i := <em>0</em>; i &lt; len(nums); i++ {<br>      if _, ok := m[nums[i]]; ok {<br>         delete(m, nums[i])<br>      } else {<br>         m[nums[i]] = nums[i]<br>      }<br>   }<br>   result := <em>0<br>   </em>for _, result := range m {<br>      return result<br>   }<br>   return result<br>}</pre><h3>使用案例：</h3><pre>func Test_singleNumber(t *testing.T) {<br>   type args struct {<br>      nums []int<br>   }<br>   tests := []struct {<br>      name string<br>      args args<br>      want int<br>   }{<br>      {&quot;test1&quot;, args{nums: []int{<em>2</em>, <em>2</em>, <em>1</em>}}, <em>1</em>},<br>      {&quot;test2&quot;, args{nums: []int{<em>4</em>, <em>1</em>, <em>2</em>, <em>2</em>, <em>1</em>}}, <em>4</em>},<br>   }<br>   for _, tt := range tests {<br>      t.Run(tt.name, func(t *testing.T) {<br>         if got := singleNumber(tt.args.nums); got != tt.want {<br>            t.Errorf(&quot;singleNumber() = <em>%v</em>, want <em>%v</em>&quot;, got, tt.want)<br>         }<br>      })<br>   }<br>}</pre><h3>Rust</h3><h3>方案1：</h3><pre>impl Solution {<br>    pub fn single_number(nums: Vec&lt;i32&gt;) -&gt; i32 {<br>        let mut result = nums[0]; <br>        for (pos, e) in nums.iter().enumerate() {<br>            if pos != 0 {<br>                result ^= e;<br>            }<br>        }<br>        return result;<br>    }<br>}</pre><h3>方案2：</h3><pre>impl Solution {<br>    pub fn single_number(nums: Vec&lt;i32&gt;) -&gt; i32 {<br>        let mut hs = std::collections::HashSet::new();<br>        for (_pos, e) in nums.iter().enumerate() {<br>           if hs.contains(e) {<br>               hs.remove(&amp;e);<br>           }<br>           else {<br>               hs.insert(e);<br>           }<br>        }<br>        for x in hs.iter() {<br>            return **x;<br>        }<br>        return 0;<br>    }<br>}</pre><h3>测试案例：</h3><pre>#[test]<br>fn test1() {<br>    let vec = vec![2,2,1];<br>    let result = Solution::single_number(vec);<br>    assert_eq!(result, 1);<br>}<br><br>#[test]<br>fn test2() {<br>    let vec = vec![4, 1, 2, 1, 2];<br>    let result = Solution::single_number(vec);<br>    assert_eq!(result, 4);<br>}</pre><h3>Kotlin:</h3><h3>方案1：</h3><pre>class Solution {<br>    fun singleNumber(nums: IntArray): Int {<br>        var result = nums[0]<br>        for (i in 1 until nums.size) {<br>            result = result xor nums[i]<br>        }<br>        return result<br>    }<br>}</pre><h3>方案2：</h3><pre>class Solution {<br>    fun singleNumber(nums: IntArray): Int {<br>        val set: MutableSet&lt;Int&gt; = HashSet()<br>        for (i in nums.indices) {<br>            val v = nums[i]<br>            if (set.contains(v)) {<br>                set.remove(v)<br>            } else {<br>                set.add(v)<br>            }<br>        }<br>        return set.toTypedArray()[0].toString().toInt()<br>    }<br>}</pre><h3>测试案例：</h3><pre>@Test<br>fun test1() {<br>    val solution = Solution()<br>    val nums = intArrayOf(2, 2, 1)<br>    val result = solution.singleNumber(nums)<br>    Assert.assertEquals(result.toLong(), 1)<br>}<br><br>@Test<br>fun test2() {<br>    val solution = Solution()<br>    val nums = intArrayOf(4, 1, 2, 1, 2)<br>    val result = solution.singleNumber(nums)<br>    Assert.assertEquals(result.toLong(), 4)<br>}</pre><h3>Python3:</h3><h3>方案1：</h3><pre>class Solution:<br>    def singleNumber(self, nums: List[int]):<br>        result = nums[0]<br>        i = 1<br>        l = len(nums)<br>        while i &lt; l :<br>            result = result ^ nums[i] <br>            i = i + 1<br>        return result</pre><h3>方案2：</h3><pre>class Solution:<br>    def singleNumber(self, nums: List[int]):<br>        s = set()<br>        for x in nums :<br>           if x in s :<br>               s.remove(x)<br>           else:<br>               s.add(x)<br><br>        return s.pop()</pre><h3>测试案例：</h3><pre>def test_singleNumber(self):<br>    s = Solution()<br>    self.assertEqual(s.singleNumber([2,2,1]), 1)<br>def test2_singleNumber(self):<br>    s = Solution()<br>    self.assertEqual(s.singleNumber([4,1,2,1,2]), 4)</pre><h3>Java:</h3><h3>方案1：</h3><pre>class Solution {<br><br>    public int singleNumber(int[] nums) {<br><br>        int result = nums[0];<br>        for (int i = 1; i &lt; nums.length; i++) {<br>            result = result ^ nums[i];<br>        }<br><br>        return result;<br>    }<br>}</pre><h3>方案2：</h3><pre>class Solution {<br><br>    public int singleNumber(int[] nums) {<br><br>        Set&lt;Integer&gt; set = new HashSet&lt;Integer&gt;();<br>        for (int i = 0; i &lt; nums.length; i++) {<br>            Integer v = nums[i];<br>            if (set.contains(v)) {<br>                set.remove(v);<br>            } else {<br>                set.add(v);<br>            }<br>        }<br>        return Integer.parseInt(set.toArray()[0].toString());<br><br>    }<br>}</pre><h3>测试案例：</h3><pre>@Test<br>public void test1() {<br><br>    Solution solution = new Solution(); <br>    int[] nums = new int[] { 2, 2, 1 };<br>    int result = solution.singleNumber(nums);<br>    Assert.assertEquals(result, 1);<br><br>}<br><br>@Test<br>public void test2() {<br>    Solution solution = new Solution(); <br>    int[] nums = new int[] { 4,1,2,1,2 };<br>    int result = solution.singleNumber(nums);<br>    Assert.assertEquals(result, 4);<br><br>}</pre><h3>C++:</h3><h3>方案1：</h3><pre>class SingleNumber {<br>public:<br>    int singleNumber(vector&lt;int&gt;&amp; nums) {<br>        int result = nums[0];<br>        int len = nums.size();<br>        for (int i = 1; i &lt; len; i++) {<br>            result = result ^ nums[i];<br>        }<br>        return result;<br>    }<br>};</pre><h3>方案2：</h3><pre>class SingleNumberWay1 {<br>public:<br>    int singleNumber(vector&lt;int&gt;&amp; nums) {<br>        unordered_set&lt;int&gt; set;<br><br>        for (int i = 0; i &lt; nums.size(); i++) {<br>            int v = nums[i];<br>            std::unordered_set&lt;int&gt;::const_iterator iter = set.find(v);<br>            if (iter== set.end()) {<br>                set.insert(v);<br>            }<br>            else {<br>                set.erase(iter);<br>            }<br>        }<br>        return  *(set.begin());<br>    }<br>};</pre><h3>测试案例：</h3><pre>TEST_METHOD(TestMethod1)<br>{<br>   SingleNumber singleNumber;<br>   int numsArray[] =  { 2, 2, 1 };<br>   vector&lt;int&gt; nums;<br>   nums.insert(nums.begin(), std::begin(numsArray), std::end(numsArray));<br>   Assert::AreEqual(1, singleNumber.singleNumber(nums));<br>}<br><br>TEST_METHOD(TestMethod2)<br>{<br>   SingleNumber singleNumber;<br>   int numsArray[] = { 4,1,2,1,2 };<br>   vector&lt;int&gt; nums;<br>   nums.insert(nums.begin(), std::begin(numsArray), std::end(numsArray));<br>   Assert::AreEqual(4, singleNumber.singleNumber(nums));<br>}</pre><h3>C#:</h3><h3>方案1：</h3><pre>public class Solution<br>{<br>    public int SingleNumber(int[] nums)<br>    {<br>        int result = nums[0];<br>        for(int i = 1; i &lt; nums.Length; i ++)<br>        {<br>            result ^= nums[i];<br>        }<br><br>        return result;<br>    }<br>}</pre><p>方案2：</p><pre>public class Solution<br>{<br>    public int SingleNumber(int[] nums)<br>    {<br>        HashSet&lt;int&gt; hs = new HashSet&lt;int&gt;();<br>        <br>        for (int i = 0; i &lt; nums.Length; i++)<br>        {<br>            if(hs.Contains(nums[i]))<br>            {<br>                hs.Remove(nums[i]);<br>            } <br>            else<br>            {<br>                hs.Add(nums[i]);<br>            }<br>        }<br>        return hs.First();<br>    }<br>}</pre><h3>测试案例：</h3><pre>[TestMethod()]<br>    public void Test1()<br>    {<br>        Solution solution = new Solution();<br>        int[] nums = { 2, 2, 1 };<br>        Assert.AreEqual(1, solution.SingleNumber(nums));<br><br>    }<br><br>    [TestMethod()]<br>    public void Test2()<br>    {<br>        Solution solution = new Solution();<br>        int[] nums = { 4, 1, 2, 1, 2 };<br>        Assert.AreEqual(4, solution.SingleNumber(nums));<br><br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0110d5c4280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You have to use hooks to achieve clean code in React]]></title>
            <link>https://medium.com/@neatcoding/you-have-to-use-hooks-to-achieve-clean-code-in-react-83cecaf6911a?source=rss-9a329162b9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/83cecaf6911a</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jet丁Neat Coding]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 04:22:10 GMT</pubDate>
            <atom:updated>2020-03-16T04:22:10.567Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will use hooks to manage the data state to React. After introducing hooks in January 2018. React has a much cleaner way to write its code.</p><p>Let’s get started.</p><p>Let’s assume we already a functional component created and we are going to apply hooks in it.</p><p>You need to import the functions first:</p><p>import React, { useState, useEffect } from ‘react’;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*l1cFVC71gilDLoJAfaFIUg.png" /></figure><p>Here is the sample code for this article:</p><p>const [data, setData] = useState([]);</p><p>const [loading, setLoading] = useState(true);</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*DvSPVIXA-dd-0l8BrcmM8A.png" /></figure><p>In the above code, we have 2 states, one is for the data, the other is loading which is a bool type to determine if the data is loaded. For each state hooks, it has a setter and a getter.</p><p>Here is how we apply the setters in this article:</p><p>useEffect(() =&gt; {</p><p>axios.get(`/api/WeatherForecast`)</p><p>.then(res =&gt; {</p><p>console.log(res.data);</p><p>setData(res.data);</p><p>setLoading(false);</p><p>}</p><p>).catch((error) =&gt; {</p><p>// handle error</p><p>console.log(error);</p><p>setLoading(false);</p><p>});</p><p>}, []);</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*8x7Vg3SHOgon4Li4HIJRyw.png" /></figure><p>We applied the hook setters when the API call is done.</p><p>Here is how we use getters:</p><p>return (</p><p>&lt;div&gt;</p><p>&lt;h1&gt; Page 1 works&lt;/h1&gt;</p><p>{loading ? &lt;Spin size=”large” tip=”Loading…” /&gt; : &lt;Table columns={columns} dataSource={data} /&gt;}</p><p>&lt;/div&gt;</p><p>);</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7pLEF7TNxmbDT5hTUAdfw.png" /></figure><p>In this demo, at the first, we use an effect to trigger the data loading, after we have the data, we applied the setters which will trigger the UI update, the UI template will display the latest data.</p><p>The logic is that the spinner will display when data is loading, the data will display while the loading is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDYwKZd1k378hKBdEG6-Qg.png" /></figure><p>That’s all for this article, please leave your comments below and see you in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83cecaf6911a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling proxy in React]]></title>
            <link>https://medium.com/@neatcoding/handling-proxy-in-react-d78009f42245?source=rss-9a329162b9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d78009f42245</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[proxy]]></category>
            <dc:creator><![CDATA[Jet丁Neat Coding]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 01:35:26 GMT</pubDate>
            <atom:updated>2020-03-16T01:35:26.078Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, let’s find the easy way of setting a proxy for React front end projects.</p><p>Let’s assume we have a backend server running on <a href="https://localhost:5001.">https://localhost:5001.</a></p><p>I assume you already have a React project up and running, otherwise, we have to create a new one.</p><pre>npx create-react-app ding-app<br>cd ding-app<br>npm start</pre><p>Inside the front end project, we want to make the request calls like this (We don’t have to add any base url at this case):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*9CAZ6LEICRk4G1hvc9lxrA.png" /></figure><p>axios.get(`/api/WeatherForecast`)</p><p>.then(res =&gt; {</p><p>console.log(res.data);</p><p>setData(res.data);</p><p>setLoading(false);</p><p>}</p><p>).catch((error) =&gt; {</p><p>// handle error</p><p>console.log(error);</p><p>});</p><p>Now, let’s prepare the proxy settings for the above purpose:</p><p>Inside package.json, let’s add the following line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*9fjWpR8OoU0s-u9nKSqrAw.png" /></figure><p>We assume we have a server running at 5001 port locally.</p><p>“proxy”: “https://localhost:5001&quot;,</p><p>After this setting is ready, you can restart your react project to make the api call. It will work now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiRYB4HhLY9HgSEAT8WziQ.png" /></figure><p>That’s all for this session.</p><p>See you in the next session. Have fun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d78009f42245" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Routing components in React]]></title>
            <link>https://medium.com/@neatcoding/routing-components-in-react-6ef020dc240?source=rss-9a329162b9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ef020dc240</guid>
            <category><![CDATA[route]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jet丁Neat Coding]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 23:48:15 GMT</pubDate>
            <atom:updated>2020-03-16T00:20:10.733Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, let’s see how we can use route among React components. Let’s assume we have 3 pages and we are going to set up the routing mechanism for them.</p><p>Here is what we are going to achieve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*gCEfBNKxHL3aFalZORcEbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*m4OuFiduEwY5Qjr0IcEDfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*NOjnLbqpmQTZZx6tfL8BcQ.png" /></figure><p>In this demo, we have 3 pages: Page 1, Page 2, Page 3.</p><p>In order to simplify the process, they are quite similar to each other.</p><p>import React from ‘react’;</p><p>function Page1() {</p><p>return (</p><p>&lt;div&gt;</p><p>&lt;h1&gt; Page 1 works&lt;/h1&gt;</p><p>&lt;/div&gt;</p><p>);</p><p>}</p><p>export default Page1;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*P3d0GIkyOLrRaalMm5QsfA.png" /></figure><p>For the dependencies, we are using react-router-dom, you need to add it to package.json:</p><p>“react-router-dom”: “5.1.2”,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*gr67xR4Ddcpya1aWVw4SLw.png" /></figure><p>To apply the routes, you will modify your parent component, for example, App.js in this demo:</p><p>import React from ‘react’;</p><p>import ‘./App.css’;</p><p>import Page1 from ‘./components/Page1’;</p><p>import Page2 from ‘./components/Page2’;</p><p>import Page3 from ‘./components/Page3’;</p><p>import { NavLink, Route, BrowserRouter } from ‘react-router-dom’;</p><p>function App() {</p><p>return (</p><p>&lt;div className=”App”&gt;</p><p>&lt;BrowserRouter&gt;</p><p>&lt;div&gt;</p><p>&lt;ul&gt;</p><p>&lt;li&gt;</p><p>&lt;NavLink activeClassName=’active’ to=”/page1&quot;&gt; Page 1&lt;/NavLink&gt;</p><p>&lt;/li&gt;</p><p>&lt;li&gt;</p><p>&lt;NavLink activeClassName=’active’ to=”/page2&quot;&gt;Page 2 &lt;/NavLink&gt;</p><p>&lt;/li&gt;</p><p>&lt;li&gt;</p><p>&lt;NavLink activeClassName=’active’ to=”/page3&quot;&gt;Page 3 &lt;/NavLink&gt;</p><p>&lt;/li&gt;</p><p>&lt;/ul&gt;</p><p>&lt;Route path=”/page1&quot; exact component={Page1}&gt;&lt;/Route&gt;</p><p>&lt;Route path=”/page2&quot; exact component={Page2}&gt;&lt;/Route&gt;</p><p>&lt;Route path=”/page3&quot; exact component={Page3}&gt;&lt;/Route&gt;</p><p>&lt;/div&gt;</p><p>&lt;/BrowserRouter&gt;</p><p>&lt;/div&gt;</p><p>);</p><p>}</p><p>export default App;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*g03zTeM9Vzww6710yc6Q6Q.png" /></figure><p>Styling:</p><p>ul{</p><p>list-style-type: none;</p><p>margin: 0;</p><p>padding: 0;</p><p>overflow: hidden;</p><p>background-color: #333;</p><p>}</p><p>li{</p><p>float: left;</p><p>}</p><p>li a {</p><p>display: block;</p><p>color: white;</p><p>text-align: center;</p><p>padding: 14px 16px;</p><p>text-decoration: none;</p><p>}</p><p>li a:hover:not(.active) {</p><p>background-color: #111;</p><p>}</p><p>.active{</p><p>background-color: #4CAF50;</p><p>}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*aEwAUZ-JaBrzlaSFrYvWPA.png" /></figure><p>Save and restart your React project, you should achieve what we had at the beginning of this article.</p><p>If you have any questions regarding this article, please comment below.</p><p>Have fun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ef020dc240" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling proxy in angular]]></title>
            <link>https://medium.com/@neatcoding/handling-proxy-in-angular-b149995abaee?source=rss-9a329162b9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b149995abaee</guid>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jet丁Neat Coding]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 22:40:39 GMT</pubDate>
            <atom:updated>2020-03-15T23:19:26.753Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling proxy in Angular</h3><p>In this article, let’s find the easy way of setting a proxy for angular front end projects.</p><p>Let’s assume we have a backend server running on <a href="https://localhost:5001.">https://localhost:5001.</a></p><p>I assume you already have an Angular project up and running, otherwise, we have to create a new one.</p><p>Inside the front end project, we want to make the request calls like this:</p><p>http.get&lt;WeatherForecast[]&gt;(‘/api/weatherforecast’).subscribe(result =&gt; {</p><p>this.forecasts = result;</p><p>}, error =&gt; console.error(error));</p><p>To achieve that, we need create a proxy json(proxy.conf.json)file like this:</p><p>{</p><p>“/api”: {</p><p>“target”: “https://localhost:5001&quot;,</p><p>“secure”: false</p><p>}</p><p>}</p><p>and then, we go to angular.json file to add the config file like this:</p><p>“serve”: {</p><p>“builder”: “@angular-devkit/build-angular:dev-server”,</p><p>“options”: {</p><p>“browserTarget”: “ding-client:build”,</p><p><strong>“proxyConfig”: “proxy.conf.json”</strong></p><p>},</p><p>“configurations”: {</p><p>“production”: {</p><p>“browserTarget”: “ding-client:build:production”</p><p>}</p><p>}</p><p>},</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*3d41lmJrKz6BOh8r3AOjSw.png" /></figure><p>That’s all we need for code change.</p><p>Let’s check it out by ng serve to start your angular project, it will be able to make the api call to your backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3pPWAW5Hom_n5xoSJ52yg.png" /></figure><p>If you see any issues, please comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b149995abaee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crack Code Interview-Add two linked lists (8 programming languages)]]></title>
            <link>https://medium.com/@neatcoding/crack-code-interview-add-two-linked-lists-8-programming-languages-60978069c507?source=rss-9a329162b9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/60978069c507</guid>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[crack-code-interview]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jet丁Neat Coding]]></dc:creator>
            <pubDate>Sun, 03 Nov 2019 04:55:53 GMT</pubDate>
            <atom:updated>2019-11-03T04:55:53.228Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Crack Code Interview-Add two linked lists (8 programming languages)</strong></p><p>You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contains a single digit. Add the two numbers and return them as a linked list.</p><p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p><p><strong>Example</strong>:</p><p>Input: (2 -&gt; 4 -&gt; 3) + (5 -&gt; 6 -&gt; 4)</p><p>Output: 7 -&gt; 0 -&gt; 8</p><p>Explanation: 342 + 465 = 807.</p><p><strong>Solution</strong>:</p><p>The linked list node data structure contains the value and the next node.</p><p>Adding two linked lists to add operations to each corresponding element;</p><p>If the calculation result exceeds 10, it needs to be shifted to the high position;</p><p>If there is a linked list, you need to add the remaining elements in the separate linked list with the last shift value of 0 or 1.</p><p>Finally check the shift value, if not zero, add as a new element.</p><p><strong>Javascript</strong>:</p><p>class ListNode {</p><p>constructor(val, next=null) {</p><p>this.val = val;</p><p>}</p><p>}</p><p>addTwoNumbers = (l1, l2)=&gt; {</p><p>let newNode = null;</p><p>let head = null;</p><p>let overTen = 0;</p><p>while(l1 != null &amp;&amp; l2 != null) {</p><p>let sum = l1.val + l2.val + overTen;</p><p>let v1 = sum % 10;</p><p>overTen = parseInt(sum / 10);</p><p>if (head == null) {</p><p>head = new ListNode(v1);</p><p>newNode = head;</p><p>}</p><p>else {</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>}</p><p>l1 = l1.next;</p><p>l2 = l2.next;</p><p>}</p><p>let l = !l1? l2 : l1;</p><p>while(l) {</p><p>let sum = l.val + overTen;</p><p>let v1 = sum % 10;</p><p>overTen = parseInt(sum / 10);</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>l = l.next;</p><p>}</p><p>if(overTen != 0) {</p><p>newNode.next = new ListNode(overTen);</p><p>}</p><p>return head;</p><p>};</p><p>{</p><p>let l1 = new ListNode(2);</p><p>l1.next = new ListNode(4);</p><p>l1.next.next = new ListNode(3);</p><p>let l2 = new ListNode(5);</p><p>l2.next = new ListNode(6);</p><p>l2.next.next = new ListNode(4);</p><p>let l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>console.log(l.val);</p><p>l = l.next;</p><p>}</p><p>console.log();</p><p>}</p><p>{</p><p>let l1 = new ListNode(1);</p><p>l1.next = new ListNode(8);</p><p>let l2 = new ListNode(0);</p><p>let l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>console.log(l.val);</p><p>l = l.next;</p><p>}</p><p>console.log();</p><p>}</p><p><strong>Java</strong>:</p><p>import java.util.*;</p><p>public class HelloWorld{</p><p>static class ListNode {</p><p>int val;</p><p>ListNode next;</p><p>ListNode(int x) { val = x; }</p><p>}</p><p>public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {</p><p>ListNode newNode = null;</p><p>ListNode head = null;</p><p>int overTen = 0;</p><p>while(l1 != null &amp;&amp; l2 != null){</p><p>int sum = l1.val + l2.val + overTen;</p><p>int v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>if(head == null){</p><p>head = new ListNode(v1);</p><p>newNode = head;</p><p>}</p><p>else{</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>}</p><p>l1 = l1.next;</p><p>l2 = l2.next;</p><p>}</p><p>ListNode l = l1 == null? l2: l1;</p><p>while(l != null){</p><p>int sum = l.val + overTen;</p><p>int v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>l = l.next;</p><p>}</p><p>if(overTen != 0){</p><p>newNode.next = new ListNode(overTen);</p><p>}</p><p>return head;</p><p>}</p><p>public static void main(String []args){</p><p>{</p><p>ListNode l1 = new ListNode(2);</p><p>l1.next = new ListNode(4);</p><p>l1.next.next = new ListNode(3);</p><p>ListNode l2 = new ListNode(5);</p><p>l2.next = new ListNode(6);</p><p>l2.next.next = new ListNode(4);</p><p>ListNode l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>System.out.print(l.val);</p><p>l = l.next;</p><p>}</p><p>System.out.println();</p><p>}</p><p>{</p><p>ListNode l1 = new ListNode(1);</p><p>l1.next = new ListNode(8);</p><p>ListNode l2 = new ListNode(0);</p><p>ListNode l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>System.out.print(l.val);</p><p>l = l.next;</p><p>}</p><p>System.out.println();</p><p>}</p><p>}</p><p>}</p><p><strong>C#</strong>:</p><p>using System;</p><p>class ListNode {</p><p>public int val;</p><p>public ListNode next;</p><p>public ListNode(int x) { val = x; }</p><p>}</p><p>class HelloWorld {</p><p>public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {</p><p>ListNode newNode = null;</p><p>ListNode head = null;</p><p>int overTen = 0;</p><p>while(l1 != null &amp;&amp; l2 != null){</p><p>int sum = l1.val + l2.val + overTen;</p><p>int v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>if(head == null){</p><p>head = new ListNode(v1);</p><p>newNode = head;</p><p>}</p><p>else{</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>}</p><p>l1 = l1.next;</p><p>l2 = l2.next;</p><p>}</p><p>ListNode l = l1 == null? l2: l1;</p><p>while(l != null){</p><p>int sum = l.val + overTen;</p><p>int v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>l = l.next;</p><p>}</p><p>if(overTen != 0){</p><p>newNode.next = new ListNode(overTen);</p><p>}</p><p>return head;</p><p>}</p><p>static void Main() {</p><p>Console.WriteLine(“Hello World”);</p><p>{</p><p>ListNode l1 = new ListNode(2);</p><p>l1.next = new ListNode(4);</p><p>l1.next.next = new ListNode(3);</p><p>ListNode l2 = new ListNode(5);</p><p>l2.next = new ListNode(6);</p><p>l2.next.next = new ListNode(4);</p><p>ListNode l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>Console.Write(l.val);</p><p>l = l.next;</p><p>}</p><p>Console.WriteLine();</p><p>}</p><p>{</p><p>ListNode l1 = new ListNode(1);</p><p>l1.next = new ListNode(8);</p><p>ListNode l2 = new ListNode(0);</p><p>ListNode l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>Console.Write(l.val);</p><p>l = l.next;</p><p>}</p><p>Console.WriteLine();</p><p>}</p><p>}</p><p>}</p><p><strong>Swift</strong>:</p><p>import Foundation</p><p>public class ListNode {</p><p>public var val: Int</p><p>public var next: ListNode?</p><p>public init(_ val: Int) {</p><p>self.val = val</p><p>self.next = nil</p><p>}</p><p>}</p><p>func addTwoNumbers(_ la: ListNode?, _ lb: ListNode?) -&gt; ListNode? {</p><p>var l1 = la</p><p>var l2 = lb</p><p>var newNode: ListNode?</p><p>var head: ListNode?</p><p>var overTen: Int = 0</p><p>while (l1 != nil &amp;&amp; l2 != nil) {</p><p>var sum: Int = l1!.val + l2!.val + overTen</p><p>var v1 = sum % 10</p><p>overTen = sum / 10</p><p>if( head == nil) {</p><p>head = ListNode(v1)</p><p>newNode = head;</p><p>}</p><p>else {</p><p>newNode!.next = ListNode(v1)</p><p>newNode = newNode!.next</p><p>}</p><p>l1 = l1!.next</p><p>l2 = l2!.next</p><p>}</p><p>var l: ListNode? = l1 == nil ? l2 : l1</p><p>while (l != nil) {</p><p>var sum = l!.val + overTen</p><p>var v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>newNode!.next = ListNode(v1);</p><p>newNode = newNode!.next;</p><p>l = l!.next;</p><p>}</p><p>if(overTen != 0) {</p><p>newNode!.next = ListNode(overTen)</p><p>}</p><p>return head</p><p>}</p><p>func test1() {</p><p>var l1: ListNode? = ListNode(2)</p><p>l1!.next = ListNode(4)</p><p>l1!.next!.next = ListNode(3)</p><p>var l2: ListNode? = ListNode(5)</p><p>l2!.next = ListNode(6)</p><p>l2!.next!.next = ListNode(4)</p><p>var l = addTwoNumbers(l1, l2)</p><p>while(l != nil) {</p><p>print(“\(l!.val)”, terminator:””)</p><p>l = l!.next</p><p>}</p><p>print(“\n”)</p><p>}</p><p>func test2() {</p><p>var l1: ListNode? = ListNode(1)</p><p>l1!.next = ListNode(8)</p><p>var l2: ListNode? = ListNode(0)</p><p>var l = addTwoNumbers(l1, l2)</p><p>while(l != nil) {</p><p>print(“\(l!.val)”, terminator:””)</p><p>l = l!.next</p><p>}</p><p>print(“\n”)</p><p>}</p><p>test1()</p><p>test2()</p><p><strong>Kotlin</strong>:</p><p>import kotlin.properties.Delegates</p><p>class ListNode {</p><p>var `val`: Int = 0</p><p>var next: ListNode? = null</p><p>constructor(v: Int) {</p><p>this.`val` = v</p><p>}</p><p>}</p><p>fun addTwoNumbers(la: ListNode?, lb: ListNode?): ListNode? {</p><p>var l1: ListNode? = la</p><p>var l2: ListNode? = lb</p><p>var newNode: ListNode? = null</p><p>var head: ListNode? = null</p><p>var overTen: Int = 0</p><p>while (l1 != null &amp;&amp; l2 != null) {</p><p>var sum: Int = l1?.`val` + l2?.`val` + overTen</p><p>var v1 = sum % 10</p><p>overTen = sum / 10</p><p>if (head == null) {</p><p>head = ListNode(v1)</p><p>newNode = head;</p><p>} else {</p><p>newNode?.next = ListNode(v1)</p><p>newNode = newNode?.next</p><p>}</p><p>l1 = l1?.next</p><p>l2 = l2?.next</p><p>}</p><p>var l: ListNode? = l1</p><p>if (l1 == null) {</p><p>l = l2</p><p>}</p><p>while (l != null) {</p><p>var sum = l?.`val` + overTen</p><p>var v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>newNode?.next = ListNode(v1);</p><p>newNode = newNode?.next;</p><p>l = l?.next;</p><p>}</p><p>if (overTen != 0) {</p><p>newNode?.next = ListNode(overTen)</p><p>}</p><p>return head</p><p>}</p><p>fun main() {</p><p>test1()</p><p>test2()</p><p>}</p><p>private fun test1() {</p><p>var l1: ListNode? = ListNode(2)</p><p>l1?.next = ListNode(4)</p><p>l1?.next?.next = ListNode(3)</p><p>var l2: ListNode? = ListNode(5)</p><p>l2?.next = ListNode(6)</p><p>l2?.next?.next = ListNode(4)</p><p>var l = addTwoNumbers(l1, l2)</p><p>while (l != null) {</p><p>print(“${l.`val`}”)</p><p>l = l?.next</p><p>}</p><p>println()</p><p>}</p><p>private fun test2() {</p><p>var l1: ListNode? = ListNode(1)</p><p>l1?.next = ListNode(8)</p><p>var l2: ListNode? = ListNode(0)</p><p>var l = addTwoNumbers(l1, l2)</p><p>while (l != null) {</p><p>print(“${l.`val`}”)</p><p>l = l?.next</p><p>}</p><p>println()</p><p>}</p><p><strong>Python</strong>:</p><p>class ListNode:</p><p>def __init__(self, x):</p><p>self.val = x</p><p>self.next = None</p><p>def addTwoNumbers(l1: ListNode, l2: ListNode) -&gt; ListNode:</p><p>newNode = None</p><p>head = None</p><p>overTen = 0</p><p>while l1 != None and l2 != None:</p><p>sum = l1.val + l2.val + overTen</p><p>v1 = sum % 10</p><p>overTen = int(sum / 10)</p><p>if head == None:</p><p>head = ListNode(v1)</p><p>newNode = head</p><p>else:</p><p>newNode.next = ListNode(v1);</p><p>newNode = newNode.next</p><p>l1 = l1.next</p><p>l2 = l2.next</p><p>l = l1 if l1 != None else l2</p><p>while l != None:</p><p>v1 = l.val</p><p>if overTen != 0:</p><p>sum = l.val + overTen</p><p>v1 = sum % 10</p><p>overTen = int(sum / 10)</p><p>newNode.next = ListNode(v1);</p><p>newNode = newNode.next</p><p>l = l.next</p><p>if overTen != 0:</p><p>newNode.next = ListNode(overTen);</p><p>return head</p><p>def test1():</p><p>l1 = ListNode(2)</p><p>l1.next = ListNode(4)</p><p>l1.next.next = ListNode(3)</p><p>l2 = ListNode(5)</p><p>l2.next = ListNode(6)</p><p>l2.next.next = ListNode(4)</p><p>l = addTwoNumbers(l1, l2)</p><p>while l != None:</p><p>print(l.val, end = ‘’)</p><p>l = l.next</p><p>print()</p><p>def test2():</p><p>l1 = ListNode(1)</p><p>l1.next = ListNode(8)</p><p>l2 = ListNode(0)</p><p>l = addTwoNumbers(l1, l2)</p><p>while l != None:</p><p>print(l.val, end = ‘’)</p><p>l = l.next</p><p>print()</p><p>test1()</p><p>test2()</p><p><strong>C++</strong>:</p><p>#include &lt;stdio.h&gt;</p><p>#include &lt;iostream&gt;</p><p>struct ListNode {</p><p>int val;</p><p>ListNode *next;</p><p>ListNode(int x) : val(x), next(NULL) {}</p><p>};</p><p>ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {</p><p>ListNode *newNode = 0;</p><p>ListNode *head = 0;</p><p>int overTen = 0;</p><p>while(l1 != 0 &amp;&amp; l2 != 0) {</p><p>int sum = l1-&gt;val + l2-&gt;val + overTen;</p><p>int v1 = sum % 10;</p><p>overTen = sum /10;</p><p>if(head == 0){</p><p>head = new ListNode(v1);</p><p>newNode = head;</p><p>}</p><p>else {</p><p>newNode-&gt;next = new ListNode(v1);</p><p>newNode = newNode-&gt;next;</p><p>}</p><p>delete l1;</p><p>delete l2;</p><p>l1 = l1-&gt;next;</p><p>l2 = l2-&gt;next;</p><p>}</p><p>ListNode* l = l1 != NULL ? l1: l2;</p><p>while(l != NULL) {</p><p>int v1 = l-&gt;val;</p><p>if(overTen != 0){</p><p>int sum = l-&gt;val + overTen;</p><p>v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>}</p><p>newNode-&gt;next = new ListNode(v1);</p><p>newNode = newNode-&gt;next;</p><p>delete l;</p><p>l = l-&gt;next;</p><p>}</p><p>if(overTen != 0) {</p><p>newNode-&gt;next = new ListNode(overTen);</p><p>}</p><p>return head;</p><p>}</p><p>void test1 () {</p><p>ListNode *l1 = new ListNode(2);</p><p>l1-&gt;next = new ListNode(4);</p><p>l1-&gt;next-&gt;next = new ListNode(3);</p><p>ListNode *l2 = new ListNode(5);</p><p>l2-&gt;next = new ListNode(6);</p><p>l2-&gt;next-&gt;next = new ListNode(4);</p><p>ListNode *l = addTwoNumbers(l1, l2);</p><p>while(l != NULL) {</p><p>std::cout &lt;&lt; l-&gt;val;</p><p>delete l;</p><p>l = l-&gt;next;</p><p>}</p><p>std::cout &lt;&lt; std::endl;</p><p>}</p><p>void test2 () {</p><p>ListNode *l1 = new ListNode(1);</p><p>l1-&gt;next = new ListNode(8);</p><p>ListNode *l2 = new ListNode(0);</p><p>ListNode *l = addTwoNumbers(l1, l2);</p><p>while(l != NULL) {</p><p>std::cout &lt;&lt; l-&gt;val;</p><p>delete l;</p><p>l = l-&gt;next;</p><p>}</p><p>std::cout &lt;&lt; std::endl;</p><p>}</p><p>int main()</p><p>{</p><p>test1();</p><p>test2();</p><p>return 0;</p><p>}</p><p><strong>Golang</strong>:</p><p>package main</p><p>import (</p><p>“fmt”</p><p>)</p><p>type ListNode struct {</p><p>Val int</p><p>Next *ListNode</p><p>}</p><p>func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {</p><p>var newNode *ListNode = nil</p><p>var head *ListNode = nil</p><p>var overTen = 0</p><p>for l1 != nil &amp;&amp; l2 != nil {</p><p>sum := l1.Val + l2.Val + overTen</p><p>v1 := sum % 10</p><p>overTen = sum /10</p><p>if head == nil {</p><p>head = &amp;ListNode{Val: v1}</p><p>newNode = head</p><p>} else {</p><p>newNode.Next = &amp;ListNode{Val: v1}</p><p>newNode = newNode.Next</p><p>}</p><p>l1 = l1.Next</p><p>l2 = l2.Next</p><p>}</p><p>l := l1</p><p>if l1 == nil {</p><p>l = l2</p><p>}</p><p>for l != nil {</p><p>v1 := l.Val;</p><p>if overTen != 0{</p><p>sum := l.Val + overTen</p><p>v1 = sum % 10</p><p>overTen = sum / 10</p><p>}</p><p>newNode.Next = &amp;ListNode{Val: v1}</p><p>newNode = newNode.Next</p><p>l = l.Next</p><p>}</p><p>if overTen != 0 {</p><p>newNode.Next = &amp;ListNode{Val: overTen }</p><p>}</p><p>return head</p><p>}</p><p>func test1() {</p><p>l1 := &amp;ListNode {Val: 2}</p><p>l1.Next = &amp;ListNode {Val: 4}</p><p>l1.Next.Next = &amp;ListNode {Val: 3}</p><p>l2 := &amp;ListNode {Val: 5}</p><p>l2.Next = &amp;ListNode {Val: 6}</p><p>l2.Next.Next = &amp;ListNode {Val: 4}</p><p>l := addTwoNumbers(l1, l2)</p><p>for l != nil {</p><p>fmt.Printf(“%d”, l.Val)</p><p>l = l.Next</p><p>}</p><p>fmt.Println();</p><p>}</p><p>func test2() {</p><p>l1 := &amp;ListNode {Val: 1}</p><p>l1.Next = &amp;ListNode {Val: 8}</p><p>l2 := &amp;ListNode {Val: 0}</p><p>l := addTwoNumbers(l1, l2)</p><p>for l != nil {</p><p>fmt.Printf(“%d”, l.Val)</p><p>l = l.Next</p><p>}</p><p>fmt.Println();</p><p>}</p><p>func main() {</p><p>test1()</p><p>test2()</p><p>}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*mXx0ODoiPjZxDfoF" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60978069c507" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[破解编程面试 — 链表的加法 （八种编程语言的实现）]]></title>
            <link>https://medium.com/@neatcoding/%E7%A0%B4%E8%A7%A3%E7%BC%96%E7%A8%8B%E9%9D%A2%E8%AF%95-%E9%93%BE%E8%A1%A8%E7%9A%84%E5%8A%A0%E6%B3%95-%E5%85%AB%E7%A7%8D%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80%E7%9A%84%E5%AE%9E%E7%8E%B0-92b60d45bf38?source=rss-9a329162b9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/92b60d45bf38</guid>
            <category><![CDATA[链表]]></category>
            <category><![CDATA[破解编程面试]]></category>
            <dc:creator><![CDATA[Jet丁Neat Coding]]></dc:creator>
            <pubDate>Sun, 03 Nov 2019 04:54:15 GMT</pubDate>
            <atom:updated>2019-11-03T04:54:15.392Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>破解编程面试 — 链表的加法 （八种编程语言的实现）</strong></h3><p><strong>破解编程面试 — -链表的加法 （八种编程语言的实现）</strong></p><p>我们有两个非空链表，它们代表两个非负整数。这些数字以相反的顺序存储，并且它们的每个节点都包含一个数字。将两个数字相加，然后将它们作为链接列表返回。</p><p>您可能会假设两个数字除了数字0本身以外都不包含任何前导零。</p><p><strong>例：</strong></p><p>输入：（2-&gt; 4-&gt; 3）+（5-&gt; 6-&gt; 4）</p><p>输出：7-&gt; 0-&gt; 8</p><p>说明：342 + 465 = 807。</p><p><strong>思路</strong>：</p><p>链表节点数据结构中包含值和下一个节点。</p><p>两个链表相加要对每个对应元素进行加操作；</p><p>如果计算结果超过了10，需要移位到高位；</p><p>如果有链表为空了，需要用最后的移位值0或者1对单独的链表中剩余的元素进行加操作；</p><p>最后再检查移位值，如果不为零，则添加为新元素。</p><p><strong>Javascript</strong>:</p><p>class ListNode {</p><p>constructor(val, next=null) {</p><p>this.val = val;</p><p>}</p><p>}</p><p>addTwoNumbers = (l1, l2)=&gt; {</p><p>let newNode = null;</p><p>let head = null;</p><p>let overTen = 0;</p><p>while(l1 != null &amp;&amp; l2 != null) {</p><p>let sum = l1.val + l2.val + overTen;</p><p>let v1 = sum % 10;</p><p>overTen = parseInt(sum / 10);</p><p>if (head == null) {</p><p>head = new ListNode(v1);</p><p>newNode = head;</p><p>}</p><p>else {</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>}</p><p>l1 = l1.next;</p><p>l2 = l2.next;</p><p>}</p><p>let l = !l1? l2 : l1;</p><p>while(l) {</p><p>let sum = l.val + overTen;</p><p>let v1 = sum % 10;</p><p>overTen = parseInt(sum / 10);</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>l = l.next;</p><p>}</p><p>if(overTen != 0) {</p><p>newNode.next = new ListNode(overTen);</p><p>}</p><p>return head;</p><p>};</p><p>{</p><p>let l1 = new ListNode(2);</p><p>l1.next = new ListNode(4);</p><p>l1.next.next = new ListNode(3);</p><p>let l2 = new ListNode(5);</p><p>l2.next = new ListNode(6);</p><p>l2.next.next = new ListNode(4);</p><p>let l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>console.log(l.val);</p><p>l = l.next;</p><p>}</p><p>console.log();</p><p>}</p><p>{</p><p>let l1 = new ListNode(1);</p><p>l1.next = new ListNode(8);</p><p>let l2 = new ListNode(0);</p><p>let l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>console.log(l.val);</p><p>l = l.next;</p><p>}</p><p>console.log();</p><p>}</p><p><strong>Java</strong>:</p><p>import java.util.*;</p><p>public class HelloWorld{</p><p>static class ListNode {</p><p>int val;</p><p>ListNode next;</p><p>ListNode(int x) { val = x; }</p><p>}</p><p>public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {</p><p>ListNode newNode = null;</p><p>ListNode head = null;</p><p>int overTen = 0;</p><p>while(l1 != null &amp;&amp; l2 != null){</p><p>int sum = l1.val + l2.val + overTen;</p><p>int v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>if(head == null){</p><p>head = new ListNode(v1);</p><p>newNode = head;</p><p>}</p><p>else{</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>}</p><p>l1 = l1.next;</p><p>l2 = l2.next;</p><p>}</p><p>ListNode l = l1 == null? l2: l1;</p><p>while(l != null){</p><p>int sum = l.val + overTen;</p><p>int v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>l = l.next;</p><p>}</p><p>if(overTen != 0){</p><p>newNode.next = new ListNode(overTen);</p><p>}</p><p>return head;</p><p>}</p><p>public static void main(String []args){</p><p>{</p><p>ListNode l1 = new ListNode(2);</p><p>l1.next = new ListNode(4);</p><p>l1.next.next = new ListNode(3);</p><p>ListNode l2 = new ListNode(5);</p><p>l2.next = new ListNode(6);</p><p>l2.next.next = new ListNode(4);</p><p>ListNode l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>System.out.print(l.val);</p><p>l = l.next;</p><p>}</p><p>System.out.println();</p><p>}</p><p>{</p><p>ListNode l1 = new ListNode(1);</p><p>l1.next = new ListNode(8);</p><p>ListNode l2 = new ListNode(0);</p><p>ListNode l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>System.out.print(l.val);</p><p>l = l.next;</p><p>}</p><p>System.out.println();</p><p>}</p><p>}</p><p>}</p><p><strong>C#</strong>:</p><p>using System;</p><p>class ListNode {</p><p>public int val;</p><p>public ListNode next;</p><p>public ListNode(int x) { val = x; }</p><p>}</p><p>class HelloWorld {</p><p>public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {</p><p>ListNode newNode = null;</p><p>ListNode head = null;</p><p>int overTen = 0;</p><p>while(l1 != null &amp;&amp; l2 != null){</p><p>int sum = l1.val + l2.val + overTen;</p><p>int v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>if(head == null){</p><p>head = new ListNode(v1);</p><p>newNode = head;</p><p>}</p><p>else{</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>}</p><p>l1 = l1.next;</p><p>l2 = l2.next;</p><p>}</p><p>ListNode l = l1 == null? l2: l1;</p><p>while(l != null){</p><p>int sum = l.val + overTen;</p><p>int v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>newNode.next = new ListNode(v1);</p><p>newNode = newNode.next;</p><p>l = l.next;</p><p>}</p><p>if(overTen != 0){</p><p>newNode.next = new ListNode(overTen);</p><p>}</p><p>return head;</p><p>}</p><p>static void Main() {</p><p>Console.WriteLine(“Hello World”);</p><p>{</p><p>ListNode l1 = new ListNode(2);</p><p>l1.next = new ListNode(4);</p><p>l1.next.next = new ListNode(3);</p><p>ListNode l2 = new ListNode(5);</p><p>l2.next = new ListNode(6);</p><p>l2.next.next = new ListNode(4);</p><p>ListNode l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>Console.Write(l.val);</p><p>l = l.next;</p><p>}</p><p>Console.WriteLine();</p><p>}</p><p>{</p><p>ListNode l1 = new ListNode(1);</p><p>l1.next = new ListNode(8);</p><p>ListNode l2 = new ListNode(0);</p><p>ListNode l = addTwoNumbers(l1, l2);</p><p>while(l != null) {</p><p>Console.Write(l.val);</p><p>l = l.next;</p><p>}</p><p>Console.WriteLine();</p><p>}</p><p>}</p><p>}</p><p><strong>Swift</strong>:</p><p>import Foundation</p><p>public class ListNode {</p><p>public var val: Int</p><p>public var next: ListNode?</p><p>public init(_ val: Int) {</p><p>self.val = val</p><p>self.next = nil</p><p>}</p><p>}</p><p>func addTwoNumbers(_ la: ListNode?, _ lb: ListNode?) -&gt; ListNode? {</p><p>var l1 = la</p><p>var l2 = lb</p><p>var newNode: ListNode?</p><p>var head: ListNode?</p><p>var overTen: Int = 0</p><p>while (l1 != nil &amp;&amp; l2 != nil) {</p><p>var sum: Int = l1!.val + l2!.val + overTen</p><p>var v1 = sum % 10</p><p>overTen = sum / 10</p><p>if( head == nil) {</p><p>head = ListNode(v1)</p><p>newNode = head;</p><p>}</p><p>else {</p><p>newNode!.next = ListNode(v1)</p><p>newNode = newNode!.next</p><p>}</p><p>l1 = l1!.next</p><p>l2 = l2!.next</p><p>}</p><p>var l: ListNode? = l1 == nil ? l2 : l1</p><p>while (l != nil) {</p><p>var sum = l!.val + overTen</p><p>var v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>newNode!.next = ListNode(v1);</p><p>newNode = newNode!.next;</p><p>l = l!.next;</p><p>}</p><p>if(overTen != 0) {</p><p>newNode!.next = ListNode(overTen)</p><p>}</p><p>return head</p><p>}</p><p>func test1() {</p><p>var l1: ListNode? = ListNode(2)</p><p>l1!.next = ListNode(4)</p><p>l1!.next!.next = ListNode(3)</p><p>var l2: ListNode? = ListNode(5)</p><p>l2!.next = ListNode(6)</p><p>l2!.next!.next = ListNode(4)</p><p>var l = addTwoNumbers(l1, l2)</p><p>while(l != nil) {</p><p>print(“\(l!.val)”, terminator:””)</p><p>l = l!.next</p><p>}</p><p>print(“\n”)</p><p>}</p><p>func test2() {</p><p>var l1: ListNode? = ListNode(1)</p><p>l1!.next = ListNode(8)</p><p>var l2: ListNode? = ListNode(0)</p><p>var l = addTwoNumbers(l1, l2)</p><p>while(l != nil) {</p><p>print(“\(l!.val)”, terminator:””)</p><p>l = l!.next</p><p>}</p><p>print(“\n”)</p><p>}</p><p>test1()</p><p>test2()</p><p><strong>Kotlin</strong>:</p><p>import kotlin.properties.Delegates</p><p>class ListNode {</p><p>var `val`: Int = 0</p><p>var next: ListNode? = null</p><p>constructor(v: Int) {</p><p>this.`val` = v</p><p>}</p><p>}</p><p>fun addTwoNumbers(la: ListNode?, lb: ListNode?): ListNode? {</p><p>var l1: ListNode? = la</p><p>var l2: ListNode? = lb</p><p>var newNode: ListNode? = null</p><p>var head: ListNode? = null</p><p>var overTen: Int = 0</p><p>while (l1 != null &amp;&amp; l2 != null) {</p><p>var sum: Int = l1?.`val` + l2?.`val` + overTen</p><p>var v1 = sum % 10</p><p>overTen = sum / 10</p><p>if (head == null) {</p><p>head = ListNode(v1)</p><p>newNode = head;</p><p>} else {</p><p>newNode?.next = ListNode(v1)</p><p>newNode = newNode?.next</p><p>}</p><p>l1 = l1?.next</p><p>l2 = l2?.next</p><p>}</p><p>var l: ListNode? = l1</p><p>if (l1 == null) {</p><p>l = l2</p><p>}</p><p>while (l != null) {</p><p>var sum = l?.`val` + overTen</p><p>var v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>newNode?.next = ListNode(v1);</p><p>newNode = newNode?.next;</p><p>l = l?.next;</p><p>}</p><p>if (overTen != 0) {</p><p>newNode?.next = ListNode(overTen)</p><p>}</p><p>return head</p><p>}</p><p>fun main() {</p><p>test1()</p><p>test2()</p><p>}</p><p>private fun test1() {</p><p>var l1: ListNode? = ListNode(2)</p><p>l1?.next = ListNode(4)</p><p>l1?.next?.next = ListNode(3)</p><p>var l2: ListNode? = ListNode(5)</p><p>l2?.next = ListNode(6)</p><p>l2?.next?.next = ListNode(4)</p><p>var l = addTwoNumbers(l1, l2)</p><p>while (l != null) {</p><p>print(“${l.`val`}”)</p><p>l = l?.next</p><p>}</p><p>println()</p><p>}</p><p>private fun test2() {</p><p>var l1: ListNode? = ListNode(1)</p><p>l1?.next = ListNode(8)</p><p>var l2: ListNode? = ListNode(0)</p><p>var l = addTwoNumbers(l1, l2)</p><p>while (l != null) {</p><p>print(“${l.`val`}”)</p><p>l = l?.next</p><p>}</p><p>println()</p><p>}</p><p><strong>Python</strong>:</p><p>class ListNode:</p><p>def __init__(self, x):</p><p>self.val = x</p><p>self.next = None</p><p>def addTwoNumbers(l1: ListNode, l2: ListNode) -&gt; ListNode:</p><p>newNode = None</p><p>head = None</p><p>overTen = 0</p><p>while l1 != None and l2 != None:</p><p>sum = l1.val + l2.val + overTen</p><p>v1 = sum % 10</p><p>overTen = int(sum / 10)</p><p>if head == None:</p><p>head = ListNode(v1)</p><p>newNode = head</p><p>else:</p><p>newNode.next = ListNode(v1);</p><p>newNode = newNode.next</p><p>l1 = l1.next</p><p>l2 = l2.next</p><p>l = l1 if l1 != None else l2</p><p>while l != None:</p><p>v1 = l.val</p><p>if overTen != 0:</p><p>sum = l.val + overTen</p><p>v1 = sum % 10</p><p>overTen = int(sum / 10)</p><p>newNode.next = ListNode(v1);</p><p>newNode = newNode.next</p><p>l = l.next</p><p>if overTen != 0:</p><p>newNode.next = ListNode(overTen);</p><p>return head</p><p>def test1():</p><p>l1 = ListNode(2)</p><p>l1.next = ListNode(4)</p><p>l1.next.next = ListNode(3)</p><p>l2 = ListNode(5)</p><p>l2.next = ListNode(6)</p><p>l2.next.next = ListNode(4)</p><p>l = addTwoNumbers(l1, l2)</p><p>while l != None:</p><p>print(l.val, end = ‘’)</p><p>l = l.next</p><p>print()</p><p>def test2():</p><p>l1 = ListNode(1)</p><p>l1.next = ListNode(8)</p><p>l2 = ListNode(0)</p><p>l = addTwoNumbers(l1, l2)</p><p>while l != None:</p><p>print(l.val, end = ‘’)</p><p>l = l.next</p><p>print()</p><p>test1()</p><p>test2()</p><p><strong>C++</strong>:</p><p>#include &lt;stdio.h&gt;</p><p>#include &lt;iostream&gt;</p><p>struct ListNode {</p><p>int val;</p><p>ListNode *next;</p><p>ListNode(int x) : val(x), next(NULL) {}</p><p>};</p><p>ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {</p><p>ListNode *newNode = 0;</p><p>ListNode *head = 0;</p><p>int overTen = 0;</p><p>while(l1 != 0 &amp;&amp; l2 != 0) {</p><p>int sum = l1-&gt;val + l2-&gt;val + overTen;</p><p>int v1 = sum % 10;</p><p>overTen = sum /10;</p><p>if(head == 0){</p><p>head = new ListNode(v1);</p><p>newNode = head;</p><p>}</p><p>else {</p><p>newNode-&gt;next = new ListNode(v1);</p><p>newNode = newNode-&gt;next;</p><p>}</p><p>delete l1;</p><p>delete l2;</p><p>l1 = l1-&gt;next;</p><p>l2 = l2-&gt;next;</p><p>}</p><p>ListNode* l = l1 != NULL ? l1: l2;</p><p>while(l != NULL) {</p><p>int v1 = l-&gt;val;</p><p>if(overTen != 0){</p><p>int sum = l-&gt;val + overTen;</p><p>v1 = sum % 10;</p><p>overTen = sum / 10;</p><p>}</p><p>newNode-&gt;next = new ListNode(v1);</p><p>newNode = newNode-&gt;next;</p><p>delete l;</p><p>l = l-&gt;next;</p><p>}</p><p>if(overTen != 0) {</p><p>newNode-&gt;next = new ListNode(overTen);</p><p>}</p><p>return head;</p><p>}</p><p>void test1 () {</p><p>ListNode *l1 = new ListNode(2);</p><p>l1-&gt;next = new ListNode(4);</p><p>l1-&gt;next-&gt;next = new ListNode(3);</p><p>ListNode *l2 = new ListNode(5);</p><p>l2-&gt;next = new ListNode(6);</p><p>l2-&gt;next-&gt;next = new ListNode(4);</p><p>ListNode *l = addTwoNumbers(l1, l2);</p><p>while(l != NULL) {</p><p>std::cout &lt;&lt; l-&gt;val;</p><p>delete l;</p><p>l = l-&gt;next;</p><p>}</p><p>std::cout &lt;&lt; std::endl;</p><p>}</p><p>void test2 () {</p><p>ListNode *l1 = new ListNode(1);</p><p>l1-&gt;next = new ListNode(8);</p><p>ListNode *l2 = new ListNode(0);</p><p>ListNode *l = addTwoNumbers(l1, l2);</p><p>while(l != NULL) {</p><p>std::cout &lt;&lt; l-&gt;val;</p><p>delete l;</p><p>l = l-&gt;next;</p><p>}</p><p>std::cout &lt;&lt; std::endl;</p><p>}</p><p>int main()</p><p>{</p><p>test1();</p><p>test2();</p><p>return 0;</p><p>}</p><p><strong>Golang</strong>:</p><p>package main</p><p>import (</p><p>“fmt”</p><p>)</p><p>type ListNode struct {</p><p>Val int</p><p>Next *ListNode</p><p>}</p><p>func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {</p><p>var newNode *ListNode = nil</p><p>var head *ListNode = nil</p><p>var overTen = 0</p><p>for l1 != nil &amp;&amp; l2 != nil {</p><p>sum := l1.Val + l2.Val + overTen</p><p>v1 := sum % 10</p><p>overTen = sum /10</p><p>if head == nil {</p><p>head = &amp;ListNode{Val: v1}</p><p>newNode = head</p><p>} else {</p><p>newNode.Next = &amp;ListNode{Val: v1}</p><p>newNode = newNode.Next</p><p>}</p><p>l1 = l1.Next</p><p>l2 = l2.Next</p><p>}</p><p>l := l1</p><p>if l1 == nil {</p><p>l = l2</p><p>}</p><p>for l != nil {</p><p>v1 := l.Val;</p><p>if overTen != 0{</p><p>sum := l.Val + overTen</p><p>v1 = sum % 10</p><p>overTen = sum / 10</p><p>}</p><p>newNode.Next = &amp;ListNode{Val: v1}</p><p>newNode = newNode.Next</p><p>l = l.Next</p><p>}</p><p>if overTen != 0 {</p><p>newNode.Next = &amp;ListNode{Val: overTen }</p><p>}</p><p>return head</p><p>}</p><p>func test1() {</p><p>l1 := &amp;ListNode {Val: 2}</p><p>l1.Next = &amp;ListNode {Val: 4}</p><p>l1.Next.Next = &amp;ListNode {Val: 3}</p><p>l2 := &amp;ListNode {Val: 5}</p><p>l2.Next = &amp;ListNode {Val: 6}</p><p>l2.Next.Next = &amp;ListNode {Val: 4}</p><p>l := addTwoNumbers(l1, l2)</p><p>for l != nil {</p><p>fmt.Printf(“%d”, l.Val)</p><p>l = l.Next</p><p>}</p><p>fmt.Println();</p><p>}</p><p>func test2() {</p><p>l1 := &amp;ListNode {Val: 1}</p><p>l1.Next = &amp;ListNode {Val: 8}</p><p>l2 := &amp;ListNode {Val: 0}</p><p>l := addTwoNumbers(l1, l2)</p><p>for l != nil {</p><p>fmt.Printf(“%d”, l.Val)</p><p>l = l.Next</p><p>}</p><p>fmt.Println();</p><p>}</p><p>func main() {</p><p>test1()</p><p>test2()</p><p>}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*dphsFT0qzdqfOU7V" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92b60d45bf38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>