0

Hi: I need someone to explain to me what this part of the code is doing: ans[(k+i)%n] = nums[i]; I understand it is placing forming a new location for the array values in i with k. What I don't understand is the %n.

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size(); // uses size of input array (old array)
        vector<int> ans(n); //new array same size
        
        for(int i = 0 ; i < n ; i++){ //new array = old array // traversing
            ans[(k+i)%n] = nums[i]; // //new array with NEW LOCATION == old array numbers
        }
        
        for(int i = 0 ; i < n ; i++)
            nums[i] = ans[i]; //putting rearrnged new array into old array (ans(i) into nums i)
    }
};
yuvi
  • 13
  • 2
  • 2
    Please invest in [some good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to learn C++ properly. Don't use so-called "competition" or "online judge" sites. Such sites are *not* any kind of teaching or learning resources, and using them as such can be actively harmful for your learning. When you decide to read a book, then the `%` operator should be explained. – Some programmer dude Feb 05 '22 at 05:21
  • Do you know modulo operation? If not, research about it. – kiner_shah Feb 05 '22 at 05:22
  • nevermind i get it haha thanks – yuvi Feb 05 '22 at 06:05
  • Sites like leetcode will help you train your problem solving skills they will not teach you (good) C++. So I would say, first learn C++ (e.g. https://www.learncpp.com/) and only then start working on solving problems using leetcode. – Pepijn Kramer Feb 05 '22 at 06:06

0 Answers0