I am basically trying to rewrite math.pow, I have the following, obviously I am not getting the concept of return values. What am I doing wrong?
public static int power(int x, int n) { if (n == 0) return 1; int i,total; for(i = 0; i < n-1 ;i++); { total = (x * total); } return total; }
You need to initialize the total value to 1.
int total = 1;
You can simply rewrite everything to:
public static int power(int x, int n) { int total = 1; for(int i = 0; i < n; i++) // i can be declared here directly { total = (x * total); } return total; // total remains 1 if n = 0 }
public static int power(int x, int n) { int total = 1; // Initialized total to 1 for(int i = 0; i < n; i++) { total = x*total; } return total; }
instead of i < n-1 you should use i <= n-1 or i < n and int total=1 . hope it works.
i < n-1
i <= n-1
i < n
int total=1
also delete ; from the end of the for loop. rewriting code
;
public static int power(int x, int n){ int total=1; for(int i = 0;i < n;i++) total *= x; return total; }
The value of the variable starts at 0. So the call to total = x*total will always be 0.
total = x*total
You need to initialize the total to x.
First, it looks like you meant:
if (n == 0) return 1;
check the power, not the base number.
You are not initialisign total , using total = x to fix what I think.
total
total = x
Here is a solution with log (n) complexity instead of linear. However, be careful with overflow.
int pow(int x, int n) { int res = 1; while(n > 0) { if(n % 2 == 1) { res = res * x; } x = x * x; n = n / 2; } return res; }
Source: https://habr.com/ru/post/1388740/More articles:use getters class or class properties? (PHP) - propertiesBackbone JS Datatable Integration - javascriptGenerics & Inheritance: What am I doing wrong here? - inheritanceD Programming: How would I read a 64-bit integer from a file? - dJava Features String / Number / currency - javaHow to determine which overloaded function is being called? - c ++LocalStorage, Looping through mapped identifiers, removing from DOM - jsonHow to compare generic member type of generic java classin - javaWindow size: how to get rid of scroll scrolling in Firefox - cssJS library best practice: return undefined or introduce error when entering the wrong function? - javascriptAll Articles