算法练习LeetCode初级算法之其他
位1的个数
解法一:
class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
return Integer.bitCount(n);
}
}
解法二:
记住一点,前面的零没用的不要!!
class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int k=0;
while (n>0) {
if (n%2==1) {
k++;
}
n/=2;
}
return k;
}
}
汉明距离
class Solution {
public int hammingDistance(int x, int y) {
int k=0;
while (x>0||y>0) {
if (x%2!=y%2) {
k++;
}
x/=2;
y/=2;
}
return k;
}
}
算法练习LeetCode初级算法之其他的更多相关文章
- 【LeetCode算法】LeetCode初级算法——字符串
在LeetCode初级算法的字符串专题中,共给出了九道题目,分别为:反转字符串,整数反转,字符串中的第一个唯一字符,有效的字母异位词,验证回文字符串,字符串转换整数,实现strStr(),报数,最 ...
- 算法练习LeetCode初级算法之链表
删除链表中的节点 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode ne ...
- 算法练习LeetCode初级算法之字符串
反转字符串 我的解法比较low,利用集合的工具类Collections.reverse反转,用时过长 class Solution { public void reverseString(char[] ...
- 算法练习LeetCode初级算法之数组
删除数组中的重复项 官方解答: 旋转数组 存在重复元素 只出现一次的数 官方解答: 同一个字符进行两次异或运算就会回到原来的值 两个数组的交集 II import java.util.Arr ...
- 算法练习LeetCode初级算法之数学
Fizz Buzz class Solution { public List<String> fizzBuzz(int n) { List<String> list=new L ...
- 算法练习LeetCode初级算法之设计问题
打乱数组 不断的让第一个与后面随机选择的数交换 class Solution { private int[] nums; private int[] initnums; public Solution ...
- 算法练习LeetCode初级算法之动态规划
爬楼梯:斐波那契数列 假设你正在爬楼梯.需要 n 阶你才能到达楼顶. 每次你可以爬 1 或 2 个台阶.你有多少种不同的方法可以爬到楼顶呢? 注意:给定 n 是一个正整数. 非递归解法 class S ...
- 算法练习LeetCode初级算法之排序和搜索
合并两个有序数组 class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { System.arrayco ...
- 算法练习LeetCode初级算法之树
二叉树的前序遍历 我的解法:利用递归,自底向下逐步添加到list,返回最终的前序遍历list class Solution { public List<Integer> preorderT ...
随机推荐
- 2018-2019-2 20165312《网络攻防技术》Exp6 信息搜集与漏洞扫描
2018-2019-2 20165312<网络攻防技术>Exp6 信息搜集与漏洞扫描 目录 一.信息搜集技术与隐私保护--知识点总结 二.实验步骤 各种搜索技巧的应用 Google Hac ...
- Logic and Proofs--离散数学
Propositions: A proposition is a declarative sentence(that is, a sentence that declares a fact ) tha ...
- awk --- 常用技巧
一.每隔几行取出一个数,输出到另外一个文件 awk '{ if (NR % 9 ==1) {print NR, " => ", $0 } }' kp.txt > xy_ ...
- [java,2019-01-15] word转pdf
word转pdf jar包 <dependency> <groupId>org.docx4j</groupId> <artifactId>docx4j& ...
- 在eclipse下,用Maven创建Spring MVC工程
参考链接:https://www.cnblogs.com/yangyxd/p/5955630.html 1.打开Eclipse,Ctrl + N 创建Maven
- [转]Python 的列表解析式,集合解析式,字典解析式
Python 的列表解析式,集合解析式,字典解析式 这三种都是 python 里面的语法糖. 语法糖,Syntactic Sugar,就是为了写程序时候少出错,发明的一些简便的方法,但不影响这个语法的 ...
- vue 单独页面body css 样式设置
给某个page下template中的第一个div设置如下样式: .body-bg { position: absolute; width: 100%; height: 100%; top:; left ...
- chrome 如何开启网页另存为.mhtml 功能
打开chrome浏览器,输入地址:chrome://flags/ 找到将网页另存为MHTML,点击启用就可以了. 或者直接输入:chrome://flags/#save-page-as-mhtml
- CentOS安装Python模块cx_Oracle
在线安装 $ wget https://bootstrap.pypa.io/get-pip.py$ python get-pip.py$ pip -V #查看pip版本 或者将网页中的代码复制到get ...
- mysql登录1045错误时 修改登录密码
1.进入 mysql 的 bin 目录下,打开 cmd ,关闭 mysql 数据库. 2.输入 mysqld --skip-grant-tables 回车. 保持窗口不要更改不要关闭 (--skip- ...