数组反转,给定长度为len的数组arr[],请将里面的元素反转, 如开始为{1,5,6,2,6,7,8} 反转后为{8,7,6,2,6,5,1}
时间: 2023-05-21 07:05:28 浏览: 120
可以使用双指针的方法进行数组反转,代码如下:
```c
void reverseArray(int arr[], int len) {
int left = 0;
int right = len - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
```
注意这里我们使用的是指针而不是索引进行数组元素的交换,这样能够提高程序的效率。
使用这个函数进行反转数组的操作就非常简单了:
```c
int main() {
int arr[] = {1, 5, 6, 2, 6, 7, 8};
int len = sizeof(arr) / sizeof(int);
reverseArray(arr, len);
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出结果为:8 7 6 2 6 5 1
相关问题
数组反转,给定长度为len的数组arr[],请将里面的元素反转, 如开始为{1,5,6,2,6,7,8} 反转后为{8,7,6,2,6,5,1}
可以使用双指针的方法来实现数组反转,具体代码如下:
```
void reverseArray(int arr[], int len) {
int left = 0, right = len - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
```
调用该函数即可实现数组反转,例如:
```
int arr[] = {1, 5, 6, 2, 6, 7, 8};
int len = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, len);
```
反转后的数组为{8,7,6,2,6,5,1}。
用python编程给定一个由整数组成的非空列表所表示的非负整数,在该数的基础上加一。 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。 你可以假设除了整数 0 之外,这个整数不会以零开头。
在Python中,给定一个非空整数列表表示的数并进行加一操作,可以采用迭代的方式来逐位处理。下面是一个简单的函数实现这个功能:
```python
def add_one(arr):
# 初始化一个空字符串用于存放结果,并从数组的最后一个元素开始遍历
result = ''
# 将数组倒序,因为我们需要从低位到高位遍历
arr.reverse()
# 遍历数组,如果当前位不是0,则直接加上1;如果是0,需要考虑进位
for digit in arr:
if digit != 9:
result += str(digit + 1)
break # 找到第一个非0位就跳出循环
else:
result += '1' # 如果是9,则进一位,添加1
carry = 1 # 记录进位
# 如果数组的所有位都是9并且有进位,那么需要在最前面添加1
if carry == 1 and len(result) > 0:
result = '1' + result
# 最后将结果反转回原来的顺序
return int(result[::-1])
# 示例
arr = [4, 3, 2, 1] # 表示的数是4321
print(add_one(arr)) # 输出:4322
阅读全文
相关推荐














