LintCode题库之–入门题库

**LintCode题库之–入门题库

1.反转一个3位整数
反转一个只有3位数的整数。
样例
样例 1:
输入: number = 123
输出: 321

样例 2:
输入: number = 900
输出: 9
注意事项: 你可以假设输入一定是一个只有三位数的整数,这个整数大于等于100,小于1000。

class Solution {
public:
    /**
     * @param number: A 3-digit number.
     * @return: Reversed number.
     */
    int reverseInteger(int number) {
        // write your code here
        int a,d,c;
        int result;
        a=number/100;
        b=(number%100)/10;
        c=number%10;
        if((c==0)&&(b!=0))
        {
            result=b*10+a;
        }
        else if((c==0)&&(b==0))
        {
            result=a;
        }
        else 
        {
            result=c*100+b*10+c;
        }
    }
};

++++++++++++++++++++++++++++
2. 交换数组两个元素
给你一个数组和两个索引,交换下标为这两个索引的数字
样例
样例 1:
输入: [1, 2, 3, 4], index1 = 2, index2 = 3
输出: 交换后你的数组应该是[1, 2, 4, 3], 不需要返回任何值,只要就地对数组进行交换即可。
样例解释: 就地交换,不需要返回值。
样例 2:
输入: [1, 2, 2, 2], index1 = 0, index2 = 3
输出: 交换后你的数组应该是[2, 2, 2, 1], 不需要返回任何值,只要就地对数组进行交换即可。
样例解释: 就地交换,不需要返回值。

class Solution {
public:
    /**
     * @param A: An integer array
     * @param index1: the first index
     * @param index2: the second index
     * @return: nothing
     */
    void swapIntegers(vector<int> &A, int index1, int index2) {
        int tmp=A[index1];
        A[index1]=A[index2];
        A[index2]=tmp;
    }
};
发布了1 篇原创文章 · 获赞 0 · 访问量 4

猜你喜欢

转载自blog.csdn.net/xudan0711/article/details/105688645
今日推荐