不使用运算符 + 和 - ,计算两整数 a 、b 之和。
示例 1:
输入: a = 1, b = 2
输出: 3
示例 2:
输入: a = -2, b = 3
输出: 1
有的朋友看到这个突然就蒙了,心里想不用+ -怎么计算两个数的和呢。朋友们不用急,接下来就告诉大家一种方法。
其实学过计算机组成原理的朋友应该知道用位运算就可以解决这个问题。
比如有两个数a和b。a ^ b是无进位的相加; a&b得到每一位的进位;我们让无进位相加的结果与进位不断的异或,直到进位为0,这样就把两个数的和计算出来了。
public class test0214 {
public static void main(String[] args) {
Solution S = new Solution();
int a ,b;
System.out.print("请输入两个数:");
Scanner in = new Scanner(System.in);
a=in.nextInt();
b=in.nextInt();
int c = S.getSum(a, b);
System.out.println("结果为:"+c);
}
}
class Solution {
public int getSum(int a, int b) {
return b == 0 ? a :getSum(a^b,(a&b)<<1);
}
}
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: "hello"
输出: "holle"
示例 2:
输入: "leetcode"
输出: "leotcede"
我的想法就是从两头同时开始判断是否为元音字母,直到两边的字母同时为元音字母时,两者交换位置。
public class test0214 {
public static void main(String[] args) {
System.out.print("变换前的:");
String s =new Scanner(System.in).nextLine();
Solution S = new Solution();
String a =S.reverseVowels(s);
System.out.println("变换后的:"+a);
}
}
class Solution {
public String reverseVowels(String s) {
char[] ch = s.toCharArray();
int left = 0;
int right = ch.length - 1;
while (left < right) {
if (!isVowel(ch[left]))
{
left ++;
}
else if (!isVowel(ch[right]))
{
right --;
}
else if (isVowel(ch[left]) && isVowel(ch[right]))
//同时为元音字母时,交换位置
{
char a =ch[left];
ch[left]= ch[right];
ch[right]= a;
left ++;
right --;
}
}
return new String(ch);
}
public static boolean isVowel(char c) {
return c == 'a' || c == 'e'
|| c == 'i' || c == 'o'
|| c == 'u' || c == 'A'
|| c == 'E' || c == 'I'
|| c == 'O' || c == 'U';
}
}