leetcode(2)

leetcode(2)

728. Self Dividing Numbers

self-dividing number is a number that is divisible by every digit it contains.

For example, 128 is a self-dividing number because 128 % 1 == 0128 % 2 == 0, and 128 % 8 == 0.

Also, a self-dividing number is not allowed to contain the digit zero.

Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.

Example 1:

Input: 
left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]

Note:

 

  • The boundaries of each input argument are 1 <= left <= right <= 10000.

class Solution {
public:
vector<int> selfDividingNumbers(int left, int right) {
vector<int> selfdividingnumber;
int temp=0;
for(;left<=right;left++)
{
temp=left;
while(temp!=0)
{
if(temp%10==0 || left%(temp%10)!=0)
break;
temp=temp/10;
}
if(temp==0)
selfdividingnumber.push_back(left);
}
return selfdividingnumber;
}
};

 

724. Find Pivot Index

Given an array of integers nums, write a method that returns the “pivot” index of this array.

We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

Example 1:

Input: 
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation: 
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.

Example 2:

Input: 
nums = [1, 2, 3]
Output: -1
Explanation: 
There is no index that satisfies the conditions in the problem statement.

Note:

 

  • The length of nums will be in the range [0, 10000].
  • Each element nums[i] will be an integer in the range [-1000, 1000].

&nbsp;

class Solution {
public:
int pivotIndex(vector<int>& nums) {
int total = 0;
if(nums.size()==0)
return -1;
for(int i:nums) total+=i;
int sum=0;
//重新认识for循环的执行顺序
for(int i=0;i<nums.size();sum += nums[i++])
{
if(sum*2==total-nums[i])
return i;
}
return -1;
}
};




So BadJust So SoGoodCoolPretty Cool (1 人已评分, 平均分: 5.00 )
Loading...

发表评论

电子邮件地址不会被公开。 必填项已用*标注