How to cyclically rotate the elements of an int array right by one in Go

1 Answer

0 votes
package main

import "fmt"

func rotateRightByOne(arr []int) []int {
	n := len(arr)

	if n == 0 {
		return arr
	}

	// Store the last element
	last := arr[n - 1]

	// Shift elements to the right
	for i := n - 1; i > 0; i-- {
		arr[i] = arr[i - 1]
	}

	// Place the last element at the first position
	arr[0] = last

	return arr
}

func main() {
	arr := []int{3, 0, 8, 5, 7}

	rotatedArr := rotateRightByOne(arr)

	fmt.Println("Rotated array:", rotatedArr)
}



/*
run:

Rotated array: [7 3 0 8 5]

*/

 



answered Oct 7, 2024 by avibootz
...