解题思路:直接将遍历链表,然后放到list中,逆向的将每一位数字*2的n-1次,并返回结果。
class Solution {
public int getDecimalValue(ListNode head) {
int sum = 0;
List list = new ArrayList<>();
while (head!=null){
list.add(head.val);
head = head.next;
}
int flag = 0;
for (int i = list.size()-1; i >=0 ; i--) {
sum+=list.get(i)*Math.pow(2,flag++);
}
return sum;
}
}
T2:1291. 顺次数
解题思路:由于题目直接给出了范围,10 <= low <= high <= 10^9。所以可以直接将范围内的顺次数全都显示出来。然后根据入参来返回结果。
class Solution {
public List sequentialDigits(int low, int high) {
List ans = new ArrayList<>();
int dict[] = {12, 23, 34, 45, 56, 67, 78, 89, 123, 234, 345, 456, 567, 678, 789, 1234, 2345, 3456, 4567, 5678, 6789, 12345, 23456, 34567, 45678, 56789, 123456, 234567, 345678, 456789, 1234567, 2345678, 3456789, 12345678, 23456789, 123456789};
for (int i = 0; i < dict.length; i++) {
if (dict[i]>=low && dict[i]<=high){
ans.add(dict[i]);
}
}
return ans;
}
public boolean canSequential(int n){
int c1 = n%10;
n=n/10;
int c2 = 0;
while (n!=0){
c2 = n%10;
n=n/10;
if (c1-c2!=1)return false;
c1=c2;
}
return true;
}
}
class Solution {
public int maxSideLength(int[][] mat, int threshold) {
int res = 0;
int n = mat.length;
for (int j = 0; j < n; j++) {
for (int k = 0; k < mat[j].length; k++) {
for (int i = res+1; i <= (mat[j].length-k>n-j?n-j:mat[j].length-k); i++) {
if (boderSize(j, k, i, mat, threshold)){
if(res < i)res = i;
}
}
}
}
return res;
}
public boolean boderSize(int L,int R,int length,int matrix[][],int threshold){
for (int i = L; i < L+length; i++) {
for (int j = R; j < R+length; j++) {
if (i>=matrix.length || j>=matrix[0].length) return false;
threshold -= matrix[i][j];
if (threshold<0)return false;
}
}
return true;
}
}