I've been trying to do this simple program where I need to check which digit of an integer number is the biggest one. So my initial thought was that I shall convert it all into an array and go with the for loop to check which element of an array is biggest. In order to do this I converted integer into String and then characters of the String into elements of an array. I ran into problem and I looked online for solution. What I don't understand is why do I need the " temp.charAt(i) - '0'" part in order to store characters of String as elements of the array. Why can't it be only arrTemp[i] = temp.charAt(i), without the "- '0'" part.
String temp = Integer.toString(n);
int arrTemp[] = new int[temp.length()];
int max = arrTemp[0];
for(int i = 0; i<temp.length(); i ) {
arrTemp[i] = temp.charAt(i) - '0';
CodePudding user response:
'0' is the character '0', not the integer 0. Characters are represented using int values (ascii code).
The ascii code for '0' is the integer value 48.
int n = (int) '0'; //n would be 48.
So, to convert '0' to the integer 0, you need to subtract '0'-'0' = 48-48 = 0
To convert '9' to int 9:
'9' - '0' = 57-48 = 9
CodePudding user response:
I don't know how to write in JavaScript so I wrote it in Python:
list = []
num = int(input("Number of integers in list: "))
for i in range(1, num 1):
ele = int(input("Enter integer: "))
list.append(ele)
print("Largest integer:", max(list))
Source: https://www.geeksforgeeks.org/python-program-to-find-largest-number-in-a-list/

