Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of exchanging digits and three steps in leetcode by golang

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you how to solve the problem of exchanging numbers and three steps in golang brush leetcode skills. The content is simple and easy to understand and the organization is clear. I hope it can help you solve your doubts. Let Xiaobian lead you to study and learn this article "how to solve the problem of exchanging numbers and three steps in golang brush leetcode skills."

Write a function that swaps the values of a and b in numbers = [a, b] without temporary variables.

Examples:

Input: numbers = [1,2]

Output: [2,1]

Tip:

numbers.length == 2

Solution:

Method 1:

summing

Method 2:

XOR

Code implementation:

func swapNumbers(numbers []int) []int { numbers[0]+=numbers[1] numbers[1]=numbers[0]-numbers[1] numbers[0]-=numbers[1] return numbers}func swapNumbers(numbers []int) []int { numbers[0]^=numbers[1] numbers[1]=numbers[0]^numbers[1] numbers[0]^=numbers[1] return numbers}

Three step problem. A child is climbing a staircase. The staircase has n steps. The child can climb one, two or three steps at a time. Implement a method to calculate how many ways a child can climb stairs. The result may be very large, you need to modulo 10000007 for the result.

Example 1:

Input: n = 3

Output: 4

Description: There are four ways to go

Example 2:

Input: n = 5

Output: 13

Tip:

n ranges between [1, 1000000]

Solution:

1, recursion

To reach step n, it can be 3 steps from step n-3, 2 steps from step n-2, or 1 step from step n-1.

2,dp

State transition equation, f (n)=f(n-3)+f(n-2)+f(n-1)

Since we're using n-3,n-2, n-1, the incremental approach

func waysToStep(n int) int { if n==1{ return 1 } if n==2{ return 2 } if n==3{ return 4 } return (waysToStep(n-3)+waysToStep(n-2)+waysToStep(n-1))00000007}func waysToStep(n int) int { dp:=make([]int,n) if n==1{ return 1 } if n==2{ return 2 } if n==3{ return 4 } dp[0]=1 dp[1]=2 dp[2]=4 for i:=3;i

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report