Input: n =31Output: 3Explanation:
* The digits of `n` are `[3, 1]`.* The possible products of any two digits are:`3 * 1 = 3`.* The maximum product is3.
Input: n =22Output: 4Explanation:
* The digits of `n` are `[2, 2]`.* The possible products of any two digits are:`2 * 2 = 4`.* The maximum product is4.
Input: n =124Output: 8Explanation:
* The digits of `n` are `[1, 2, 4]`.* The possible products of any two digits are:`1 * 2 = 2`,`1 * 4 = 4`,`2 * 4 = 8`.* The maximum product is8.
classSolution {
public:int maxProduct(int n) {
vector<int> d;
while (n) {
d.push_back(n %10);
n /=10;
}
int ans =0;
for (int i =0; i < d.size(); ++i) {
for (int j = i; j < d.size(); ++j) {
int prod = d[i] * d[j];
if (prod > ans) ans = prod;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funcmaxProduct(nint) int {
d:= []int{}
forn > 0 {
d = append(d, n%10)
n/=10 }
ans:=0fori:=0; i < len(d); i++ {
forj:=i; j < len(d); j++ {
prod:=d[i] *d[j]
ifprod > ans {
ans = prod }
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
publicintmaxProduct(int n) {
List<Integer> d =new ArrayList<>();
while (n > 0) {
d.add(n % 10);
n /= 10;
}
int ans = 0;
for (int i = 0; i < d.size(); i++) {
for (int j = i; j < d.size(); j++) {
int prod = d.get(i) * d.get(j);
if (prod > ans) ans = prod;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funmaxProduct(n: Int): Int {
val d = mutableListOf<Int>()
var x = n
while (x > 0) {
d.add(x % 10)
x /=10 }
var ans = 0for (i in d.indices) {
for (j in i until d.size) {
val prod = d[i] * d[j]
if (prod > ans) ans = prod
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defmaxProduct(self, n: int) -> int:
d: list[int] = []
while n >0:
d.append(n %10)
n //=10 ans =0for i in range(len(d)):
for j in range(i, len(d)):
prod = d[i] * d[j]
if prod > ans:
ans = prod
return ans
impl Solution {
pubfnmax_product(n: i32) -> i32 {
letmut d =vec![];
letmut x = n;
while x >0 {
d.push(x %10);
x /=10;
}
letmut ans =0;
for i in0..d.len() {
for j in i..d.len() {
let prod = d[i] * d[j];
if prod > ans {
ans = prod;
}
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
maxProduct(n: number):number {
constd: number[] = [];
while (n>0) {
d.push(n%10);
n= Math.floor(n/10);
}
letans=0;
for (leti=0; i<d.length; i++) {
for (letj=i; j<d.length; j++) {
constprod=d[i] *d[j];
if (prod>ans) ans=prod;
}
}
returnans;
}
}