剑指offer——66. 构建乘积数组

66. 构建乘积数组

题目链接

NowCoder

题目描述

给定一个数组 A[0, 1,…, n-1],请构建一个数组 B[0, 1,…, n-1],其中 B 中的元素 B[i]=A[0]*A[1]*…*A[i-1]*A[i+1]*…*A[n-1]。要求不能使用除法。


解题思路

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
31
class Solution {
public:
int strToInt(string str) {
long long res = 0;
if(str.empty()) return res;
//去空格
int index = 0;
while(index < str.size() && str[index] == ' ') index ++;
//去± 做标记
bool isMinus = false;
if(str[index] == '+') index ++;
else if(str[index] == '-')
{
index ++;
isMinus = true;
}
//构建整数
for(int i = index; i < str.size(); i ++)
{
if(str[i] >= '0' && str[i] <= '9')
{
res = res * 10 + str[i] - '0';
}
else break; //不合法 跳出
}
if(isMinus) res *= -1;
if(res < INT_MIN) res = INT_MIN;
if(res > INT_MAX) res = INT_MAX;
return (int)res;
}
};
创作不易,欢迎打赏!
-------------本文结束感谢您的阅读-------------