/* * @lc app=leetcode id=461 lang=rust * * [461] Hamming Distance * * https://leetcode.com/problems/hamming-distance/description/ * * algorithms * Easy (71.14%) * Total Accepted: 283.7K * Total Submissions: 398.8K * Testcase Example: '1\n4' * * The Hamming distance between two integers is the number of positions at * which the corresponding bits are different. * * Given two integers x and y, calculate the Hamming distance. * * Note: * 0 ≤ x, y < 2^31. * * * Example: * * Input: x = 1, y = 4 * * Output: 2 * * Explanation: * 1 (0 0 0 1) * 4 (0 1 0 0) * ⁠ ↑ ↑ * * The above arrows point to positions where the corresponding bits are * different. * * */ impl Solution { pub fn hamming_distance(x: i32, y: i32) -> i32 { (x ^ y).count_ones() as i32 // let mut res = 0; // while x > 0 || y > 0 { // if (x & 1) != (y & 1) { res += 1; } // x = x >> 1; // y = y >> 1; // } // res } } // pub structSolution; use std::collections::HashMap; use std::collections::HashSet; use std::fmt::Debug; use std::hash::Hash; use std::iter::FromIterator; #[allow(dead_code)] pub fn print_map(map: &HashMap) { for (k, v) in map.iter() { println!("{:?}: {:?}", k, v); } } #[allow(dead_code)] pub fn say_vec(nums: Vec){ println!("{:?}", nums); } #[allow(dead_code)] pub fn char_frequency(s: String) -> HashMap { let mut res:HashMap = HashMap::new(); for c in s.chars(){ *res.entry(c).or_insert(0) += 1; } res } #[allow(dead_code)] pub fn vec_counter(arr: Vec) -> HashMap { let mut c = HashMap::new(); for n in arr { *c.entry(n).or_insert(0) += 1; } c } #[allow(dead_code)] pub fn vec_to_hashset(arr: Vec) -> HashSet { HashSet::from_iter(arr.iter().cloned()) }