-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Checky-Hu
committed
Feb 11, 2020
1 parent
8db414b
commit c14231b
Showing
2 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
[package] | ||
name = "reordered-power-of-2" | ||
version = "0.1.0" | ||
authors = ["Checky-Hu <[email protected]>"] | ||
edition = "2018" | ||
|
||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||
|
||
[dependencies] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
use std::env; | ||
use std::str::FromStr; | ||
|
||
struct Solution {} | ||
|
||
impl Solution { | ||
fn helper( | ||
bytes: &[u8], | ||
index: usize, | ||
len: usize, | ||
flags: &mut Vec<bool>, | ||
result: &mut String, | ||
) -> bool { | ||
if index == len { | ||
let mut t: i32 = i32::from_str(result).unwrap_or(0); | ||
while t != 1 { | ||
if t & 1 == 0 { | ||
t >>= 1; | ||
} else { | ||
return false; | ||
} | ||
} | ||
true | ||
} else { | ||
for i in 0..len { | ||
if flags[i] || (index == 0 && bytes[i] == b'0') { | ||
continue; | ||
} | ||
flags[i] = true; | ||
result.push(bytes[i] as char); | ||
if Solution::helper(bytes, index + 1, len, flags, result) { | ||
return true; | ||
} | ||
result.pop(); | ||
flags[i] = false; | ||
} | ||
false | ||
} | ||
} | ||
|
||
pub fn reordered_power_of2(n: i32) -> bool { | ||
let s: String = n.to_string(); | ||
let len: usize = s.len(); | ||
let mut flags: Vec<bool> = vec![false; len]; | ||
let mut result: String = String::new(); | ||
Solution::helper(s.as_bytes(), 0, len, &mut flags, &mut result) | ||
} | ||
} | ||
|
||
fn main() { | ||
let mut ret: i32 = 0; | ||
for (index, arg) in env::args().enumerate() { | ||
if 1 == index { | ||
ret += 1; | ||
let n: i32 = i32::from_str(&arg).expect("Error parse."); | ||
println!( | ||
"Power of 2 after reorder: {}", | ||
Solution::reordered_power_of2(n) | ||
); | ||
break; | ||
} | ||
} | ||
|
||
if 0 == ret { | ||
println!("Require at least one parameter."); | ||
} | ||
} |