-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path171. Excel Sheet Column Number
30 lines (25 loc) · 1.19 KB
/
171. Excel Sheet Column Number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution { //second approach, saves memory
public:
int titleToNumber(string columnTitle) {
int len=columnTitle.length(),sum=0;
for(int i=0;i<len;i++)
sum+=(columnTitle[i]-64) * pow(26,(len-1)-i); //-64 is used to get 1 for 'A', 2 for 'B'..etc
return sum;
}
};
/*Runtime: 0 ms, faster than 100.00% of C++ online submissions for Excel Sheet Column Number.
Memory Usage: 6.1 MB, less than 28.55% of C++ online submissions for Excel Sheet Column Number.*/
// class Solution { //first approach, used map
// public:
// int titleToNumber(string columnTitle) {
// int len=columnTitle.length(),sum=0;
// map<char,int> m={{'A',1},{'B',2},{'C',3},{'D',4},{'E',5},{'F',6},{'G',7},{'H',8},
// {'I',9},{'J',10},{'K',11},{'L',12},{'M',13},{'N',14},{'O',15},{'P',16},
// {'Q',17},{'R',18},{'S',19},{'T',20},{'U',21},{'V',22},{'W',23},{'X',24},
// {'Y',25},{'Z',26}};
// for(int i=0;i<len;i++)
// sum+=m[columnTitle[i]] * pow(26,(len-1)-i);
// return sum;
// }
// };
/*8 ms, 8.3 MB*/